firebase - 属性 'docs' 不能无条件访问,因为收到可以是 'null' Flutter

标签 firebase flutter dart dart-null-safety

迁移到空安全后显示此错误。我现在该怎么办?

  Widget chatMessages() {
    return StreamBuilder(
        stream: messageStream,
        builder: (context, snapshot) {
          return snapshot.hasData
              ? ListView.builder(
                  padding: EdgeInsets.only(bottom: 70, top: 16),
                  itemCount: snapshot.data.docs.length,
                  reverse: true,
                  itemBuilder: (context, index) {
                    DocumentSnapshot ds = snapshot.data.docs[index];
                    return chatMessageTitle(
                        ds["message"], myUserName == ds["sendBy"]);
                  })
              : Center(child: CircularProgressIndicator());
        });
  }
添加空检查 (!) 后显示此错误
              itemCount: snapshot.data!.docs.length,
              reverse: true,
              itemBuilder: (context, index) {
                DocumentSnapshot ds = snapshot.data!.docs[index];

最佳答案

你必须投snapshot.data到它的类型。假设类型是 QuerySnapshot (将其更改为 snapshot.data 的实际类型)。

(snapshot.data! as QuerySnapshot).docs.length
我们可以指定 stream 的类型,而不是在所有位置进行类型转换。在 StreamBuilder .
StreamBuilder<QuerySnapshot>(
  ...
);
现在 snapshot.data推断为 QuerySnapshot并且不需要类型转换。
snapshot.data!.docs.length

关于firebase - 属性 'docs' 不能无条件访问,因为收到可以是 'null' Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66670247/

相关文章:

Flutter 更改下拉箭头颜色

firebase - 是否有 Firestore 的 Dart 接口(interface) - 使用 https ://firebase. google.com/docs/firestore/quickstart 中的 API?

Android Google Map 和 firebase 依赖问题

android - 带有操作按钮和图像的 Flutter 本地通知

flutter - 如何在 SliverList 周围包裹卡片?

dart - Redstone Mapper 卡在 pub get 上

java - 具有自定义身份验证的 Firebase Java 客户端

node.js - 从 firebase 函数连接到 MongoDB Atlas

flutter 错误 : A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'

ios - iOS 上单页的 Flutter 设备方向