firebase FlutterstreamSnapshot.data.docs不工作

nnvyjq4y  于 2023-01-14  发布在  Flutter
关注(0)|答案(3)|浏览(118)

尝试获取我的流快照长度,但由于某些原因,.docs不起作用。它说不能在对象上调用docs,但我不明白为什么它将我的streamSnapshot读取为对象,而它应该是一个流。

return Scaffold(
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('chats/khgvkhvfkftkh/messages')
            .snapshots(),
        builder: (ctx, streamSnapshot) {
          if (streamSnapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final documents =
              streamSnapshot.data.docs.length;
          return ListView.builder(
            itemCount: documents.length, //does not work due to error in declaration of documents
            itemBuilder: (ctx, index) => Container(
jecbmhm3

jecbmhm31#

您要将documents设置为docs属性的**长度

final documents = streamSnapshot.data.docs.length;

所以当你以后做documents.length的时候,那是streamSnapshot.data.docs.length.length,它实际上并不存在。
给定变量名,我希望将documents设置为:

final documents = streamSnapshot.data.docs;
5lhxktic

5lhxktic2#

return Scaffold(
//Just change the type of streamBuilder from object to dynamic, it will solve the error.
      body: StreamBuilder<dynamic>(
          stream: FirebaseFirestore.instance
              .collection('chats/k4dtLMCeacmpFMBf8sA9/messages')
              .snapshots(),
          builder: (ctx, streamSnapshot) {
            if (streamSnapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
            return ListView.builder(
              itemCount: streamSnapshot.data!.docs.length,
              itemBuilder: (ctx, index) => Container(
                padding: const EdgeInsets.all(8),
                child: const Text('This Works'),
              ),
            );
          }),
hof1towb

hof1towb3#

如果您是第一次遇到这个挑战,解决方案是定义StreamBuilder构建器属性,如下所示

return Scaffold(
  body: StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Add your collection specific url')
        .snapshots(),
    builder:(ctx, AsyncSnapshot<dynamic>streamSnapshot){ //Change here
      if(streamSnapshot.connectionState == ConnectionState.waiting){
        return Center(
          child: CircularProgressIndicator(),
        );
      }
     return ListView.builder(
        itemCount:streamSnapshot.data.docs.length,
        itemBuilder: (ctx, index)=>Container(
            padding: EdgeInsets.all(20),
            child: const Text('This works')
        ),
      );
    },
  ),

相关问题