import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final messageTextController = TextEditingController();
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
Future<void> sendMessage() async {
// 获取当前用户
final user = _auth.currentUser;
if (user != null) {
// 发送消息到Firestore的messages集合
final message = {
'text': messageTextController.text,
'sender': user.email,
};
await _firestore.collection('messages').add(message);
messageTextController.clear();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat Screen'),
),
body: StreamBuilder(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final messages = snapshot.data.documents.reversed;
return Column(
children: [
// 循环显示每条消息
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) => ListTile(
title: Text(messages[index]['text']),
subtitle: Text(messages[index]['sender']),
),
),
),
// 输入消息的文本框和发送按钮
Divider(),
Container(
decoration: BoxDecoration(
border: Border(top: BorderSide()),
),
child: Row(
children: <Widget>[
Expanded(
child: TextField(
controller: messageTextController,
decoration: InputDecoration(hintText: 'Type your message'),
评论已关闭