错误:未为类型“对象”定义操作“[]”

问题描述

我正在使用 Null -Safety 然后我不断收到这个错误,在我的代码中使用快照的任何地方

这里是错误

error

这是我的代码

StreamBuilder(
                          stream: firestore
                              .collection('interest')
                              .doc('${auth.currentUser?.uid}')
                              .snapshots(),builder: (context,snapshot) {
                            if (!snapshot.hasData) {
                              return Center(
                                child: CircularProgressIndicator(),);
                            }
                            return ListView.builder(
                                scrollDirection: Axis.horizontal,itemCount: snapshot.data!['Interest'].length,itemBuilder: (context,index) {
                                  return Padding(
                                    padding: const EdgeInsets.only(top: 12.0),child: bottomCardList(
                                      'assets/1 (6).jpeg',snapshot.data!['Interest'][index]
                                          .toString(),),);
                                });
                          }),

谢谢

解决方法

我通过使用类型来解决这个问题

StreamBuilder<DocumentSnapshot<Map>>(
                          stream: firestore
                              .collection('interest')
                              .doc('${auth.currentUser?.uid}')
                              .snapshots(),builder: (context,snapshot) {
                            if (!snapshot.hasData) {
                              return Center(
                                child: CircularProgressIndicator(),);
                            }
return ListView.builder(
                                scrollDirection: Axis.horizontal,itemCount: snapshot.data!['Interest'].length,itemBuilder: (context,index) {
                                  return Padding(
                                    padding: const EdgeInsets.only(top: 12.0),child: bottomCardList(
                                      'assets/1 (6).jpeg',snapshot.data!['Interest'][index]
                                          .toString(),),);
                                });
                          }),
,

有几个解决方案:

  • 为您的 StreamBuilder 提供一个类型:

    StreamBuilder<DocumentSnapshot<Map>> (...)
    
  • builder 的第二个参数提供类型:

    builder: (context,AsyncSnapshot<Map> snapshot)
    
  • 使用 asObject 向下转换为 Map

    (snapshot.data as Map)['key']