没有为类“对象”定义运算符“[]”。扑
Posted
技术标签:
【中文标题】没有为类“对象”定义运算符“[]”。扑【英文标题】:The operator '[]' isn't defined for the class 'Object'. flutter 【发布时间】:2021-10-24 01:01:37 【问题描述】:我正在尝试从 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');
【问题讨论】:
我认为右括号在错误的地方NetworkImage(document?.data())['image']
非常感谢您的时间和回答。现在这是错误lib/widgets/category_list.dart:56:74: Error: The operator '[]' isn't defined for the class 'NetworkImage'. - 'NetworkImage' is from 'package:flutter/src/painting/image_provider.dart' ('/C:/flutter/packages/flutter/lib/src/painting/image_provider.dart'). Try correcting the operator to an existing operator, or defining a '[]' operator. backgroundImage: NetworkImage(document?.data())['image'],
【参考方案1】:
我猜你把QueryDocumentSnapshot
和DocumentSnapshot
混淆了。这是因为有两种不同的snapshots()
方法(一种来自Query
类,一种来自DocumentReference
类)。
改变这个:
children: snapshot.data.docs.map((DocumentSnapshot document)
到这里:
children: snapshot.data.docs.map((QueryDocumentSnapshot document)
【讨论】:
感谢您的回复,但添加该行并不能解决错误。【参考方案2】:改用这个:
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(),
),
让我知道结果。
【讨论】:
以上是关于没有为类“对象”定义运算符“[]”。扑的主要内容,如果未能解决你的问题,请参考以下文章
C++运算符重载中 重载为类的成员函数和重载为类的友元函数 的区别是啥?