flutter中streambuilder内的类型化流

8e2ybdfx  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(137)

我使用的流在streamBuilder中返回groupmodel类型,但我无法访问构建器中的数据。

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');
            }
          },
        ));

如果我修改firebase中的值,我可以看到一个空输出

log(snapshot.data.toString());
xzv2uavs

xzv2uavs1#

在从firestore获取数据之前,你试图通过一个Stream调用一个map()列表,首先是null,直接在StreamBuilder中使用那个Stream,你需要等待QuerySnapshot到达,然后根据它在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');
            }
          },
        ));

相关问题