【问题标题】:Unable to access the documents in streambuilder无法访问 streambuilder 中的文档
【发布时间】:2022-01-29 05:20:53
【问题描述】:

大家好,我正在尝试构建一个流构建器来访问我的云存储,但由于我无法将这些文档用于我的应用程序,因此我无法执行 Streamsnapshot.data.doc

这是我的流生成器​​代码:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ChatScreen extends StatelessWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
        stream: FirebaseFirestore
            .instance 
            .collection('chats')
            .snapshots(), 
        builder: (ctx, streamSnapshot) {
          if (streamSnapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          return ListView.builder(
              itemCount: streamSnapshot.data,   **//not able to add .documents.length after this**
              itemBuilder: (ctx, index) => Container(
                    padding: EdgeInsets.all(8.0),
                    child: Text('This is working'),
                  ));
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
      ),
    );
  }
}

【问题讨论】:

  • 试试streamSnapshot.data!.docs.length,确保数据不为空。
  • 我刚试过没用

标签: firebase flutter firebase-realtime-database google-cloud-firestore flutter-layout


【解决方案1】:

您必须像这样在 StreamBuilder 上添加对象的类型:

StreamBuilder<YourObject>

之后,您将从streamSnapshot 访问documents

【讨论】:

  • 如果我这样做,我会收到此错误 - “参数类型 'Stream>>' 不能分配给参数类型 'Stream ?'。”
  • 这是因为你传错了类型。 YourObject 类型必须与快照类型相同。
猜你喜欢
  • 2016-02-25
  • 1970-01-01
  • 2020-05-25
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
  • 1970-01-01
相关资源
最近更新 更多