Need I do pagination for flutter StreamBuilder?

Viewed 67

I'm new to flutter, and now I'm creating an app which has a feed page, I'm using StreamBuilder + firestore to do this, the code is like this:

return StreamBuilder(
            stream: FirebaseFirestore.instance
                .collection('posts')
                .orderBy('createdAt', descending: true)
                .snapshots(),
            builder: (context,
                AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(
                  child: CircularProgressIndicator(
                    color: primaryColor,
                  ),
                );
              }
              return ListView.builder(
                itemCount: snapshot.data!.docs.length,
                itemBuilder: (context, index) => Container(
                  child: createPostViewFromSnapShot(snapshot.data!.docs[index]),// it returns a widget
                ),
              );
            },
          );

You can see from the code I didn't do pagination, I want to know when the code runs, it fetch all the post from firestore ? Or it will fetch data by block or something like pagination ?

I want to know if it's necessary to do pagination for StreamBuilder?

1 Answers
  1. Avoid creating Widgets in Methods. That way you cause your App to become I'm-performant. Because the Widget is not sat directly in the Tree, but a method, every build that methods gets called, no matter if the resulting widget would have to be actually be rebuilt.
  2. That stream will not always emit events where data is not null. You will most likely get an exception for using snapshot.data! bang operator
  3. Take a closer look at the documentation: https://firebase.flutter.dev/docs/firestore/usage/

FlutterFire provides support for dealing with realtime changes to collections and documents. A new event is provided on the initial request, and any subsequent changes to collection/document whenever a change occurs (modification, deleted or added).

For what you are trying to achieve, it would be better to initially fetch a limited set of documents from your collection.

collectionReference.limit(42).get()

You can than fetch the next elements by using https://firebase.flutter.dev/docs/firestore/usage/#start--end-cursors

Related