【问题标题】:Flutter streamSnapshot.data.docs not working颤振 streamSnapshot.data.docs 不工作
【发布时间】:2021-11-02 22:16:04
【问题描述】:

试图获取我的流快照长度,但由于某种原因 .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(

【问题讨论】:

    标签: firebase flutter stream


    【解决方案1】:

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

    final documents = streamSnapshot.data.docs.length;
    

    所以当你以后做documents.length时,那是streamSnapshot.data.docs.length.length,它确实不存在。

    鉴于变量名称,我希望您想将 documents 设置为:

    final documents = streamSnapshot.data.docs;
    

    【讨论】:

    • 嘿弗兰克!虽然你是绝对正确的,如果我的代码在那里,那将是我的下一个错误哈哈,但我似乎已经通过在我的流构建器中调用 streamSnapshot 时声明 来修复它。感谢您参与我在 Stack 上的第一个问题!
    【解决方案2】:
    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'),
                  ),
                );
              }),
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 2018-10-11
    • 2021-12-11
    • 2022-01-25
    • 2020-07-12
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多