Home > Mobile >  StreamBuilder not returning CircularProgressIndicator when waiting for Firebase connection
StreamBuilder not returning CircularProgressIndicator when waiting for Firebase connection

Time:08-13

I have a StreamBuilder that isn't displaying a CircularProgressIndicator when waiting for the results from the Firebase connection. I just end up receiving a generic Null check operator used on a null value error because of the dirty state. The error disappears once the connection is established and the snapshot is returned.

StreamBuilder(
          stream: FirebaseFirestore.instance.collection('posts').snapshots(),
          builder: (context,
              AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }
            return ListView.builder(
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) => PostCard(
                snap: snapshot.data!.docs[index].data(),
              ),
            );
          }),

Why doesn't it render the CircularProgressIndicator if Connection.State == waiting?

As replied in comments below. I am receiving the error:

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. The client will operate in offline mode until it is able to successfully connect to the backend.

Running on Android Emulator and the connection is stable/fast so not sure why it's happening.

CodePudding user response:

Firestore snapshots, when loading new ones, are so quick you almost never will see the CircularProgressIndicator.

Furthermore, you're using a else clause that includes any other case. What happens is that when the code reaches this line:

itemCount: snapshot.data!.docs.length,

data is null and therefore you've got yourself a null check error.

Try the following:

final a = StreamBuilder(
  stream: FirebaseFirestore.instance.collection('posts').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }

    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data!.docs.length,
        itemBuilder: (context, index) => PostCard(
          snap: snapshot.data!.docs[index].data(),
        ),
      );
    }

    // TODO properly handle error cases
    print(snapshot.stackTrace);
    print(snapshot.error);
    return const Text('Something went wrong');
  },
);

When you'll try this there's a good chance you'll see Something went wrong: you need to investigate why your snapshots haven't got data.

  • Related