I am building an App with Flutter using Firebase as a "backend". I have to display quite long and complex to build lists and was wondering if there was a more performance-based approach than my current approach:
This is what I do at the moment:
Widget build(BuildContext context) {
return StreamBuilder(
stream: Firestore.instance.collection("collection" ).limit(200).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator());
} else {
return _buildComplexeList(snapshot);
}
},
);
This leads to following problem: Every time something gets updated in the list all widgets are rebuilt within the list. Also, I wanted to use an AnimatedList and it is quite hard to find out whether an item was added or not and if yes, where it was added.
I was wondering if you could use
.snapshots().listen((event) { }
which returns a StreamSubscription instead of a stream, but to be honest I have no idea how. This could help to only build the changed widgets.
It would be great to know if some of you have some other and better solution approaches. Thanks in advance!
Paul
If you are using ListView.builder
, fear not. They are optimized to only build visible widgets, as can be seen in the documentation linked above. Based on a quick look at the AnimatedList
documentation, it looks like performance would not be an issue there as well, due to the stated similarities to ListView.builder
.
As far as figuring out changes between two different snapshots, Firebase has you covered. .snapshots()
returns a Stream<QuerySnapshot>
s, and each QuerySnapshot
has a field called documentChanges
, which itself is a List<DocumentChange>
. You can iterate through this list and see exactly what changes were made to each document, as shown in this untested snipet:
for (final documentChange in snapshot.data.documentChanges) {
// todo process this individual document change here
}
Listening to the stream yourself is always an option for more control, but StreamBuilder
abstracts this away from you to speed up development. You probably don't need to do this. If you did want to, you would have to make sure to clean up any StreamSubscription
s created in a State's dispose method.
Notes: Instead of calling a method to build your list, consider using a widget class instead. Also, it is typically a good idea to abstract your data source (in this case, Firebase) away from the UI by making a wrapper around it, but this is by no means a requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With