Home > Software engineering >  Typed stream inside a streambuilder in flutter
Typed stream inside a streambuilder in flutter

Time:12-12

I am using stream who return groupmodel type in a streamBuilder but i am not able to reach the data in the builder.

StreamBuilder<GroupModel>(
          stream: groups
              .where('users', arrayContains: firebaseAuth.currentUser?.uid)
              .snapshots()
              .map((QuerySnapshot<Object> res) =>
                  GroupModel.fromJson(res as Map<String, dynamic>)),
          builder: (BuildContext context, AsyncSnapshot<GroupModel> snapshot) {
            log(snapshot.data.toString());
            if (snapshot.hasData) {
              return Text(snapshot.data.toString());
            } else {
              return const Text('No data');
            }
          },
        ));

If i modify the value in firebase i can see a null output from

    log(snapshot.data.toString());

CodePudding user response:

You're trying to call a map() list over a Stream which will be null at first before getting data from firestore, using that Stream directly in StreamBuilder, you need to wait for the QuerySnapshot to arrive, then act based on its value on the StreamBuilder :

StreamBuilder<QuerySnapshot>(
          stream: groups
              .where('users', arrayContains: firebaseAuth.currentUser?.uid)
              .snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasData) {
            final userDoc = snapshot.data!.docs.first;
            final data = userDoc.data() as Map<String, dynamic>;
            final model = GroupModel.fromJson(data);
              return Text("${data}, ${model}");
            } else {
              return const Text('No data');
            }
          },
        ));
  • Related