这是我设置stream
StreamController<List<MessageFromCloudDetail>> _messageFromCloudDetail;
这是向其中添加数据的方式
ChatApiClient().fetchDetail(http.Client(),documentId).then((data){
_messageFromCloudDetail.add(data);
});
这是我的streambuilder
StreamBuilder <List<MessageFromCloudDetail>>(
stream:_messageFromCloudDetail.stream,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
default:
return new Flexible(
child: ChatBuilder(
querySnapshot: snapshot.data,
userFullname: userFullname,
userId: userId,
roomId: documentId),
);
}
}),
首次加载/打开时,显示数据。但是,当我尝试添加这样的新数据
ChatApiClient().inputDetail(documentId, userId, _textController.text ).then((result){
// [{"chatDetailId":"3","roomId":"1","from":"2","messageContent":"4","createdDate":"2019-12-02 13:53:25","chatImage":null}]
_messageFromCloudDetail.sink.add(result);
});
但是它正在更改为新的json而不是添加新的数据。所以我的问题是,如何向流中添加新数据?
注意:请不要告诉我再次重新加载所有数据。
这里是日志
第一个加载页面
I/flutter (19129): AsyncSnapshot<List<MessageFromCloudDetail>>(ConnectionState.waiting, null, null)
I/flutter (19129): AsyncSnapshot<List<MessageFromCloudDetail>>(ConnectionState.active, [Instance of 'MessageFromCloudDetail'], null)
我提交一些东西之后
W/IInputConnectionWrapper(19129): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(19129): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(19129): getTextAfterCursor on inactive InputConnection
I/flutter (19129): AsyncSnapshot<List<MessageFromCloudDetail>>(ConnectionState.active, [Instance of 'MessageFromCloudDetail'], null)
我的课
class MessageFromCloudDetail {
String roomId;
String from;
String messageContent;
String createdDate;
String chatImage;
MessageFromCloudDetail(
{this.roomId, this.from, this.messageContent, this.createdDate, this.chatImage});
factory MessageFromCloudDetail.fromJson(Map<String, dynamic> json) {
return MessageFromCloudDetail(
roomId: json['roomId'] as String,
from: json['from'] as String,
messageContent: json['messageContent'] as String,
createdDate: json['createdDate'] as String,
chatImage: json['chatImage'] as String
);
}
}
答案 0 :(得分:1)
我认为您只是用最新数据替换旧数据。我不知道您的数据结构如何构成,但您可能需要将新数据附加到最旧的数据上。
答案 1 :(得分:0)
感谢@pskink。我已经解决了问题,这是我添加新数据的方式
首先,我更改了第一次加载数据的方式
List<MessageFromCloudDetail> listMessage = <MessageFromCloudDetail>[];
listMessage =
await ChatApiClient().fetchDetail(http.Client(), documentId);
if (this.mounted) {
_messageFromCloudDetail.sink.add(listMessage);
}
然后
Future _handleSubmitted(String text) async {
MessageFromCloudDetail newMessage;
newMessage = MessageFromCloudDetail(
messageContent: _textController.text,
from: userId,
createdDate: DateTime.now().toString(),
chatImage: "");
listMessage.add(newMessage);
listMessage.sort((a, b) => b.createdDate.compareTo(a.createdDate));
_messageFromCloudDetail.sink.add(listMessage);
_textController.text = "";
}