How to cache Firebase data in Flutter?

后端 未结 1 1135
走了就别回头了
走了就别回头了 2020-12-09 21:57

In my app I build a list of objects using data from Firebase. Inside a StreamBuilder, I check if the snapshot has data. If it doesen\'t, I am returning a simple Text widget

相关标签:
1条回答
  • 2020-12-09 22:18

    To be sure whether the data is coming from Firestore's local cache or from the network, you can do this:

              for (int i = 0; i < snapshot.data.documents.length; i++) {
                DocumentSnapshot doc = snapshot.data.documents.elementAt(i);
                print(doc.metadata.isFromCache ? "NOT FROM NETWORK" : "FROM NETWORK");
    

    In the case you described you are probably going to still see the loading screen when its "NOT FROM NETWORK". This is because it does take some time to get it from the local cache. Soon you will be able to ask for the query's metadata for cases with empty results.

    Like others suggested, you can cache the results and you won't see this. First you can try to cache it in the Widget using something like:

      QuerySnapshot cache; //**
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: StreamBuilder(
            initialData: cache, //**
            stream: Firestore.instance.collection('events').snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Text("Loading...");
              }
              cache = snapshot.data; //**
    

    This will make your widget remember the data. However, if this does not solve your problem, you would have to save it not in this widget but somewhere else. One option is to use the Provider widget to store it in a variable that lives beyond the scope of this particular widget.

    Probably not related, but it's also a good idea to move the Firestore.instance.collection('events').snapshots() to initState(), save the reference to the stream in a private field and use that it StreamBuilder. Otherwise, at every build() you may be creating a new stream. You should be ready for build() calls that happen many times per second, whatever the reason.

    0 讨论(0)
提交回复
热议问题