简体   繁体   中英

Flutter & Firebase: reduce the number of reads with StreamBuilder

I'm building a ranking page with Firebase Firestore as follows:

StreamBuilder<QuerySnapshot>(
                        stream: FirebaseFirestore.instance
                            .collection('user')
                            .orderBy('total_score', descending: true)
                            .limit(3)
                            .snapshots(includeMetadataChanges: false),
                        builder:...

Everything is working almost perfectly, but I have only one problem: the number of readings is too high, I tried to limit it to 3 but it still reaches a very high number and with only 1 user.

For other pages I use cached data, which reduces the number of reads.

Is this possible in StreamBuilder? Any suggestion?

For StatefulWidget stream api will gets call every state changes. Create a state variable for stream,

  late final myStream = FirebaseFirestore.instance
      .collection('user')
      .orderBy('total_score', descending: true)
      .limit(3)
      .snapshots(includeMetadataChanges: false);
  @override
  Widget build(BuildContext context) {

and use it on

StreamBuilder<QuerySnapshot>(
     stream: myStream  

You can check Fixing a common FutureBuilder and StreamBuilder problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM