Error:The method '[]' can't be unconditionally invoked because the receiver can be 'null'

Error:The method '[]' can't be unconditionally invoked because the receiver can be 'null'

我刚刚转换了我的项目 Null Safety,但我收到错误提示

The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').   

我有点困惑,我不知道该怎么办。

 return ListView.builder(
                                    scrollDirection: Axis.horizontal,
                                    itemCount: snapshot.data['Interest'].length ,// i am getting error here
                                    itemBuilder: (context, index) {
                                      return Padding(
                                        padding: const EdgeInsets.only(top: 12.0),
                                        child: bottomCardList(
                                            'assets/1 (6).jpeg',
                                            snapshot.data['Interest'][index]// i am getting error here
                                                .toString(),
                                            () {}),
                                      );
                                    });
                              }),

谢谢

发生的事情是,切换到 null 安全后,您不能直接使用 can 为 null 的变量编写语句,而不检查它们是否为 null。在这种情况下,变量 snapshot.data 可以为空,因此您必须相应地编写代码。尝试将您的代码转换为:

return ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: snapshot.data!['interest'].length,
  // i am getting error here
  itemBuilder: (context, index) {
    return Padding(
      padding: const EdgeInsets.only(top: 12.0),
      child: bottomCardList(
        'assets/1 (6).jpeg',
        snapshot.data?['Interest'][index] // i am getting error here
            .toString(),
      ),
    );
  },
);

现在,有了这个,您的 itemCount 错误应该消失了(如果没有,请更新您的 cloud_firestore 插件,它不是 null 安全的)。至于您在 bottomCardList 遇到的错误,这取决于您的 bottomCardList 参数是否为 null 安全。如果 bottomCardList 的类型是 bottomCardList(String someVar, String someOtherVar),则可以将其更改为 bottomCardList(String someVar, String? someOtherVar)。然后,在 bottomCardList 代码中,您必须确保处理的是 someOtherVar 可以为 null 的情况。

您可以观看此视频了解更多信息:https://www.youtube.com/watch?v=iYhOU9AuaFs


编辑 对于“未定义对象错误”:

我假设您的构建器参数类似于:

builder: (context, snapshot) {
    return ListBuilder etc. etc. 
}
                

尝试将其更改为:

builder: (context, AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
    return ListBuilder etc. etc. 
}

错误应该消失了。 DocumentSnapshot 是如果你正在做 collection.docs.snapshots()。如果您正在执行 collection.snapshots(),请使用 QuerySnapshot 等

我通过给 StreamBuilder 一个类型解决了这个问题。

StreamBuilder<DocumentSnapshot<Map>>

问题:

从可空类型的映射中检索值时出现此错误,即 Map?。假设您有:

Map? map;

您正在访问它

int i = map['0']; // <-- Error

解法:

  1. 提供默认值(推荐)

    int i = map?['0'] ?? -1;
    
  2. 如果确定值不是 null,请使用 Bang 运算符。

    int i = map!['0'];