![](/img/trans.png)
[英]The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'
[英]The operator '[]' isn't defined for the type 'QuerySnapshot<Object?>' Try defining the operator '[]' - Flutter
我想设置,
ListView.builder's itemcount
to firebase's users collection's group(field) list length(你可以在下图看到)
我尝试下面的图片
我的尝试:
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("users").snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
final isCollectionEmpty = snapshot.data!.docs.isEmpty;
final DocumentsWhichContainsPosts = snapshot.data!.docs.where(
(doc) =>
(doc.data() as Map<String, dynamic>)["groups"].isNotEmpty);
if (DocumentsWhichContainsPosts.isNotEmpty) {
return ListView.builder(
itemCount: snapshot.data!['groups'].length, // this shows error
itemBuilder: ((context, index) {
return Text("data");
}),
);
} else {
return Container(
child: Center(child: Text("No posts")),
);
}
} else {
return const Center(
child: CircularProgressIndicator(color: Colors.red),
);
}
});
当此代码运行时,显示此错误
未为类型“QuerySnapshot<Object?>”定义运算符“[]”尝试定义运算符“[]”
itemCount: snapshot.data!['groups'].length, // this shows error
这显示了一个错误,因为这里的snapshot.data
是一个QuerySnapshot
,它没有[]
操作。 如果要返回QuerySnapshot
中的文档数,请使用:
itemCount: snapshot.data!.size,
然后在项目构建器中,您可以通过以下方式从每个文档中获取数据:
itemBuilder: ((context, index) {
return Text(snapshot.data!.docs[index]("groups").length);
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.