Reputation: 6135
I am developing a chat system in mobile application using Flutter
/ Dart
.
I have fetched a user's message records from server by API and received result as Future<dynamic>
. This result has list of chat data. If I pass it to FutureBuilder
widget. It works and lists chat records in listTile
. Everything is working well.
When user adds a new chat message then I post the that text message to server by API to store into database. It works and response status is 200 which means message has been added on server's database.
I have instance of newly added chat message, I want to append / add it to previously fetched Future<dynamic>
result.
Kindly suggest me how can I do this? Can we update Future<dynamic>
typed data? Thanks.
Upvotes: 0
Views: 269
Reputation: 3862
Future
can emit only one item by design. If you want to emit multiple items, use Stream
: https://api.flutter.dev/flutter/dart-async/Stream-class.html
To get to know how to generate streams have a look on this: https://dart.dev/articles/libraries/creating-streams
Most likely what you want to do is use rxdart
's BehaviorSubject
or dart's StreamController
(they share api, so just substitute the name, except for ValueStream
, which is specific to rxdart, this one will have to be replaced with just Stream
):
class Api {
final _subject = BehaviorSubject<DataToDisplay>();
ValueStream<DataToDisplay> get data => _subject.stream;
void fetchData() {
final data = downloadDataFromSomewhere();
_subject.add(data);
}
}
Then just create a StreamBuilder
similarly to FutureBuilder
.
Upvotes: 1