display loading screen until firestore returns some data flutter

25 Views Asked by At

I have this code to retrieve data from firestore

    Stream<QuerySnapshot> collectionStream({
    required String path,
    QueryBuilder? queryBuilder,
  }) {
    return _streamErrorHandler(
      () {
        Query<Map<String, dynamic>> reference =
            firebaseFirestore.collection(path);
        if (queryBuilder != null) {
          reference = queryBuilder(reference);
        }
        return reference.snapshots();
      },
    );
  }

It works fine with a little hack. And I use riverpod to listen to the stream of data

final myDataAsync = ref.watch(myDataProvider);
...
myDataAsync.when(
      data: (data) => DataScreen(),
      error: (e, st) => Padding(
        padding: const EdgeInsets.all(Sizes.ten),
        child: Text("Error"),
      ),
      loading: () => const DataPlaceHolder(),

Sometimes I will get this warning:

Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds. This typically indicates that your device does not have a healthy Internet connection at the moment.

It happens with the android emulator as well as with real device Basically I am not in loading state anymore but data state and since I am not getting any data from firestore yet I get a white screen which doesn't feel good from user perspective. I would like to still display the loading screen until data are available, but I don't know how to check that.

1

There are 1 best solutions below

0
Andreas Hadjimamas On

Use FutureBuilder and snapshot.hasData to check if your app has loaded the data from firestore

FutureBuilder(
future: collectionStream(),
builder: (context,snapshot){
if(snapshot.hasData){
return Text('Your Data') //Any Widget o display your data
}else{
return const Center(
    child: CircularProgressIndicator(color: Color(0xFF00BFFF)),
  );
}
}