问题描述
我不知道如何创建状态 addComment 并返回 Widget 去我按下按钮
我不知道如何用 val in 返回 ListTile
List<CommentDetail> comments = [
CommentDetail(
otherUsername: "b-akused02",otherUserProfileImageUrl: Utils.getRandomImageUrl(),comment: "Nice Nice Nice Nice Nice Nice",date: "3 days"),];
这是我的失败代码
class CommentsPage extends StatefulWidget {
@override
_CommentsPageState createState() => _CommentsPageState();
}
class CommentDetail {
String comment;
String otherUsername;
String otherUserProfileImageUrl;
String date;
CommentDetail(
{@required this.comment,@required this.otherUsername,@required this.otherUserProfileImageUrl,@required this.date});
}
class _CommentsPageState extends State<CommentsPage> {
List<CommentDetail> comments = [
CommentDetail(
otherUsername: "b-akused02",];
var txt = TextEditingController();
void _addComment(String val) {
setState(() {
comments.add(val);
});
}
Widget _buildCommentList() {
return ListView.builder(itemBuilder: (context,index) {
if (index < comments.length) {
return _buildCommentItem(comments[index]);
}
});
}
Widget _buildCommentItem({
@required String comment,@required String otherUsername,@required String otherUserProfileImageUrl,@required String date,}) {
return ListTile(//comment Box inside),
解决方法
你快到了
您在 _buildCommentItem 函数中传递的是一个 CommentDetail 对象。
此外,在收到 CommentDetail 对象后,您只需像往常一样填充 ListTile。
Widget _buildCommentList() {
return ListView.builder(itemBuilder: (context,index) {
if (index < comments.length) {
return _buildCommentItem(commentDetail: comments[index]);
}
});
}
Widget _buildCommentItem({
@required CommentDetail commentDetail
}) {
return ListTile(
title: Text(commentDetail.comment),);
}