此streambuilder似乎仅在每次热重载时显示数据库中的消息(以及我发送的任何新消息)。我怀疑小部件在从流中接收信息之前会自行构建自身的问题,但我不确定如何解决此问题。
谢谢。
class MessagesStream extends StatefulWidget {
MessagesStream({this.chatroomId});
final String chatroomId;
@override
_MessagesStreamState createState() =>
_MessagesStreamState(chatroomId: chatroomId);
}
class _MessagesStreamState extends State<MessagesStream> {
_MessagesStreamState({this.chatroomId});
String chatroomId;
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _firestore
.collection('chatrooms')
.document(widget.chatroomId)
.collection(widget.chatroomId)
.orderBy('timestamp', descending: true)
.limit(20)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
}
return Expanded(
child: ListView.builder(
itemCount: snapshot.data.documents.length,
reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
itemBuilder: (context, index) {
DocumentSnapshot message = snapshot.data.documents[index];
final messageText = message.data['text'];
final messageSender = message.data['sender'];
final currentUser = loggedInUser.email;
//a separate widget for the layout of each message bubble
return MessageBubble(
text: messageText,
isMe: currentUser == messageSender ? true : false,
);
},
),
);
},
);
}
}