Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Pre-load data into Firestore local cache on the first load

I've implemented Cloud Firestore into my Flutter app and encountered this problem: if there's no network connection on the very first load of the app (after installation), no data is shown. My question is: How to make so that the data from Firestore is shown on the first load (after installation) even without internet connection? My code for fetching data is this:

class QuestionsListState extends State<QuestionsList> {
  @override
  Widget build(BuildContext context) {

    return new StreamBuilder<QuerySnapshot>(
      stream: _questionsCollectionReference
          .where("category", isEqualTo: _chosenCategory).orderBy("order").snapshots,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return const Text('');
        final int messageCount = snapshot.data.documents.length;
        return new ListView.builder(
          itemCount: messageCount,
          itemBuilder: (_, int index) {
            final DocumentSnapshot document = snapshot.data.documents[index];
            return new ListTile(
              title: new FlatButton(
                  onPressed: () {
                    Navigator.push(context, new MaterialPageRoute(
                      builder: (BuildContext context) => new AddAnswerDialog(),
                      fullscreenDialog: true,
                    ));
                  },
                  child: new Text(
                    document['text'],
                    style: new TextStyle(fontSize: 18.0, color: Colors.blue),
                  )),
            );
          },
        );
      },
    );
  }
}
like image 712
Darkhan Avatar asked Apr 10 '18 11:04

Darkhan


1 Answers

I ran into a similar situation. The solution for me was to load that data from disk, by using a FutureBuilder instead of const Text('')

In other words, your structure would be:

  • StreamBuilder
    • when hasData is false
      • FutureBuilder
        • when hasData is false
          • show a CircularProgress
        • when hasData is true
          • show disk data
    • when hasData is true
      • show online data

For a first-time user, this will show a CircularProgress, followed by data from disk, followed by online data. If the online data does not load (no network), the user keeps seeing the disk data.

like image 157
Andrei Tudor Diaconu Avatar answered Oct 24 '22 15:10

Andrei Tudor Diaconu