flutter 实现评论区widget
时间: 2023-07-28 20:10:08 浏览: 94
要在 Flutter 中实现评论区 Widget,你可以创建一个自定义的 StatefulWidget,其中包含一个输入框和一个评论列表。用户可以在输入框中输入评论并提交,评论将被添加到评论列表中。以下是一个简单的示例代码:
```dart
class CommentWidget extends StatefulWidget {
@override
_CommentWidgetState createState() => _CommentWidgetState();
}
class _CommentWidgetState extends State<CommentWidget> {
TextEditingController _controller = TextEditingController();
List<String> _comments = [];
void _addComment() {
setState(() {
_comments.add(_controller.text);
_controller.clear();
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(
hintText: "写下你的评论",
suffixIcon: IconButton(
icon: Icon(Icons.send),
onPressed: _addComment,
),
),
onSubmitted: (String value) {
_addComment();
},
),
Expanded(
child: ListView.builder(
itemCount: _comments.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_comments[index]),
);
},
),
),
],
);
}
}
```
在这个示例代码中,我们首先创建了一个 CommentWidget StatefulWidget。在 StatefulWidget 的状态类 _CommentWidgetState 中,我们定义了一个 TextEditingController 和一个 List 来存储评论。在 build 方法中,我们创建了一个包含输入框和评论列表的 Column。在输入框中,我们使用 TextField 组件来接受用户的输入,并添加了一个 IconButton 来提交评论。在评论列表中,我们使用 ListView.builder 组件来渲染评论列表,并使用 ListTile 组件来显示每条评论的内容。
你可以将 CommentWidget 组件添加到你的 Flutter 页面中来展示评论区,并通过调用 setState 方法来更新评论列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)