Home > Software engineering >  how do I turn off data reloading from firebase while using FlutterFire_ui?
how do I turn off data reloading from firebase while using FlutterFire_ui?

Time:05-11

I am using googles flutter fire ui library and for the most part it is working fine, the only problem is there doesn't seem to be anyway listed to stop the snapshots from refreshing whenever the data changes.

here's my query:

 final restaurantsQuery =
        FirebaseFirestore.instance.collection('restaurants').orderBy('name');

and here's the code:

class RestrauntSliver extends StatelessWidget {
  const RestrauntSliver({
    Key? key,
    required this.restaurantsQuery,
  }) : super(key: key);

  final Query<Map<String, dynamic>> restaurantsQuery;

  @override
  Widget build(BuildContext context) {
    return FirestoreQueryBuilder<Map<String, dynamic>>(
      query: restaurantsQuery,
      builder: (context, snapshot, _) {
        if (snapshot.isFetching) {
          return SliverToBoxAdapter(child: const CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Text('Something went wrong! ${snapshot.error}');
        }

        // ...

        return SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              // obtain more items
              if (snapshot.hasMore && index   1 == snapshot.docs.length) {
                // Tell FirestoreQueryBuilder to try to obtain more items.
                // It is safe to call this function from within the build method.
                snapshot.fetchMore();
              }
              final restaurant = snapshot.docs[index].data();

              final restaurantId = snapshot.docs[index].id;
              // print(restaurant);
              return RestaurantItem(
                restaurant: restaurant,
                id: restaurantId,
              );
            },
            childCount: snapshot.docs.length,
          ),
        );
      },

    );
  }
}

CodePudding user response:

The FirestoreQueryBuilder will automatically unsubscribe from realtime listeners if the widget is destroyed.

If you need more control about when to cancel, pause or resume a listener, I would recommend to use a StreamSubscription instead.

You can cancel your StreamSubscription by calling its cancel() method (i.e. you are not interested in receiving any more data updates from the stream). Example code from the docs, adjusted to query for the first 10 cities alphabetically with:

final query = db.collection("cities").orderBy("name").limit(10);
final listener = query.snapshots().listen((event) {
  // ...
});
listener.cancel();

Link to the relevant part of the docs: https://firebase.google.com/docs/firestore/query-data/listen?hl=en

  • Related