1

我正在尝试从 firebase 数据库中获取数据。我收到此错误:

未为类“对象”定义运算符“[]”

尝试了很多方法,但错误仍然存​​在。

StreamBuilder<QuerySnapshot>(
            stream: _categoryProvider.category.snapshots(),
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
              if(snapshot.hasError){
                return Text('Something went wrong..');
              }
              if(snapshot.connectionState == ConnectionState.waiting){
                return Center(child: CircularProgressIndicator(),);
              }
              return Expanded(
                child: ListView(
                  children: snapshot.data.docs.map((DocumentSnapshot document){
                      return ListTile(
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(document?.data()['image']),// error is on this line
                        ),
                        //title: Text(document.data()['category name']),
                        onTap: (){},
                      );
                    }).toList(),
                ),
              );
              }),

这里是 CategoryProvider。

import 'package:cloud_firestore/cloud_firestore.dart';

class CategoryProvider{
  CollectionReference category = FirebaseFirestore.instance.collection('categories');
}
4

2 回答 2

1

我猜你QueryDocumentSnapshotDocumentSnapshot. 这是因为有两种不同snapshots()的方法(一种来自Query类,一种来自DocumentReference类)。

改变这个:

children: snapshot.data.docs.map((DocumentSnapshot document){

对此:

children: snapshot.data.docs.map((QueryDocumentSnapshot document) {
于 2021-08-23T17:57:52.820 回答
0

改用这个:

final temp = document.data; // once try this and if it did not work use json.decode(document.data)
return Expanded(
                child: ListView(
                  children: snapshot.data.docs.map((DocumentSnapshot document){
                      return ListTile(
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(temp['image']),// error is on this line
                        ),
                        //title: Text(temp['category name']),
                        onTap: (){},
                      );
                    }).toList(),
                ),

让我知道结果。

于 2021-08-23T17:48:56.387 回答