Losing data when user terminates app then runs it again

Viewed 17

I use firebase in almost all my app and after a doc is added I add it to a variable to structure the data and organize it but however when app is terminated then ran again the variable resets although firebase docs are added to it in the first place.

How can I fix that?

An example clarifying what I mean:

    //add to firebase 
final doc = <String, dynamic>{
                'docType':'firebase'
    };
              await collection.add(doc);
//add to a model's variable

context.read<Model>().addDoc(doc['docType']);
1 Answers

You can listen to the stream of your snapshots, so when ever data is received you can add it to your model

//You can add that in initState for example
subscription = CloudFirestoreManager.readData.listen(
   (data) async {
      //Add received data to model
   },
);



class CloudFirestoreManager {
  static Stream<QuerySnapshot<Map<String, dynamic>>> get snapshots {
    return firestoreInstance
        .collection('my-id')
        .snapshots();
  }

  static FirebaseFirestore get firestoreInstance {
    return FirebaseFirestore.instance;
  }

  static Stream<List<Map<String, dynamic>>> get readData => snapshots.map(
        (snapshot) => snapshot.docs
            .map(
              (doc) => doc.data(),
            )
            .toList(),
      );
}
Related