Flutter 错误:方法';[]和#x27;can';不能无条件地调用,因为接收方可以是';空';

Flutter 错误:方法';[]和#x27;can';不能无条件地调用,因为接收方可以是';空';,flutter,dart,dart-null-safety,Flutter,Dart,Dart 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(

我只是将我的项目转换为空安全性,我得到的错误是

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(),
                                            () {}),
                                      );
                                    });
                              }),

感谢

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

返回ListView.builder(
滚动方向:轴水平,

itemCount:snapshot.data!['interest'].length, //我在这里出错了 itemBuilder:(上下文,索引){ 返回填充( 填充:仅限常量边集(顶部:12.0), 孩子:最下面的卡片列表( “资产/1(6).jpeg”,
snapshot.data?['Interest'][index]//我在这里遇到了错误 .toString(), ), ); }, );
现在,有了这个,itemCount的错误应该消失了(如果没有,请更新您的cloud\u firestore插件,它不是空安全的)。至于您在bottomCardList得到的错误,这取决于您的bottomCardList参数是否为空安全。如果bottomCardList的类型为bottomCardList(String someVar,String someOtherVar),则可以将其更改为bottomCardList(String someVar,String?someOtherVar)。然后,在bottomCardList代码中,您必须确保您正在处理someOtherVar可以为null的情况

您可以查看此视频以了解更多信息:


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

我假设您的生成器参数类似于:

builder:(上下文,快照){
返回ListBuilder等。
}
尝试将其更改为:

builder:(上下文,异步快照){
返回ListBuilder等。
}

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

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

StreamBuilder<DocumentSnapshot<Map>>
StreamBuilder

问题:

从可为空类型的映射(即
map?
)检索值时会出现此错误。假设你有:

地图?地图;
你正在访问它


int i=map['0'];//snapshot.data['Interest']可以为空,因此您可以这样检查:snapshot.data['Interest']!=无效的快照。数据['Interest']。长度:0@JorgeVieira还是给了我errorsnapshot.data!['interest'].长度。。。我以前尝试过这个方法,但仍然显示errorsnapshot.data?['Interest'][index]//即使使用了这个,我在这里也遇到了错误。toString()。我已经试过了,但仍然显示了错误,错误到底是怎么说的?还是以前的错误吗?没有为类型“object”定义操作“[]”。请检查我添加到答案中的编辑