这是使用streambuilder和列表视图从firestore获取消息文本的代码。我不知道为什么_buildlistitem不起作用。我也尝试打印数字来检查它,但没有用。有人可以帮忙吗
Widget _buildMessagesList() {
print(1);
return StreamBuilder(
stream:
_chatService.getMessages(widget.receiveruid, _auth.currentUser!.uid),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text('Loading');
}
if (snapshot.data == null) {
return Text('No data available');
} else {
return ListView(
children: snapshot.data!.docs
.map((doc) => _buildMessageItem(doc))
.toList(),
);
}
},
);
}
Widget _buildMessageItem(DocumentSnapshot document) {
Map<String, dynamic> data = document.data() as Map<String, dynamic>;
print(3);
var alignment = (data['senderId'] == _auth.currentUser!.uid)
? Alignment.centerRight
: Alignment.centerLeft;
return Container(
alignment: alignment,
child: Column(
children: [
Text(data['senderEmail']),
Text(data['message']),
],
),
);
}
我想在代码中调用函数_buildMessageItem。
上课
ChatService
在方法中
Stream<QuerySnapshot> getMessages(String userId, String otherUserId)
将'时间戳'更改为'时间'
错误
.orderBy('timestamp', descending: false)
固定
.orderBy('time', descending: false)
Stream<QuerySnapshot> getMessages(String userId, String otherUserId) {
List<String> ids = [userId, otherUserId];
ids.sort();
String chatRoomId = ids.join("_");
print(2);
return _store
.collection('chat_rooms')
.doc(chatRoomId)
.collection('messages')
.orderBy('time', descending: false)
.snapshots();
}
在消息映射中使用
'time': timestamp,
Map<String, dynamic> toMap() {
return {
'senderId': senderid,
'senderEmail': senderemail,
'receiverId': receiverid,
'message': message,
'time': timestamp,
};
}