帮我用 flutter 写一个聊天页面
时间: 2023-06-18 10:06:21 浏览: 120
好的,以下是一个简单的聊天页面示例代码:
```dart
import 'package:flutter/material.dart';
class ChatPage extends StatefulWidget {
@override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
final TextEditingController _textController = TextEditingController();
final List<ChatMessage> _messages = [];
void _handleSubmitted(String text) {
_textController.clear();
ChatMessage message = ChatMessage(
text: text,
isMe: true,
);
setState(() {
_messages.insert(0, message);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat'),
),
body: Column(
children: <Widget>[
Flexible(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
reverse: true,
itemCount: _messages.length,
itemBuilder: (_, int index) => _messages[index],
),
),
Divider(height: 1.0),
Container(
decoration: BoxDecoration(color: Theme.of(context).cardColor),
child: _buildTextComposer(),
),
],
),
);
}
Widget _buildTextComposer() {
return IconTheme(
data: IconThemeData(color: Theme.of(context).accentColor),
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: <Widget>[
Flexible(
child: TextField(
controller: _textController,
onSubmitted: _handleSubmitted,
decoration:
InputDecoration.collapsed(hintText: 'Send a message'),
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: Icon(Icons.send),
onPressed: () => _handleSubmitted(_textController.text),
),
),
],
),
),
);
}
}
class ChatMessage extends StatelessWidget {
ChatMessage({this.text, this.isMe});
final String text;
final bool isMe;
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(right: 16.0),
child: CircleAvatar(child: Text('User')),
),
Expanded(
child: Column(
crossAxisAlignment:
isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: <Widget>[
Text('User', style: Theme.of(context).textTheme.subtitle1),
Container(
margin: EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
],
),
);
}
}
```
在这个示例中,我们使用了 `TextField` 和 `ListView` 来实现聊天界面。当用户在文本框中输入消息并按下发送按钮时,将创建一个新的 `ChatMessage` 对象并添加到 `_messages` 列表中。`ListView` 将会自动更新以显示新消息。最后,我们使用 `CircleAvatar` 和 `Text` 来显示用户的头像和名称。
你可以将这个代码复制到你的 Flutter 项目中并运行,然后你就可以在应用中查看一个简单的聊天界面了。
阅读全文