我在关注一个类,他使用Image.network(snapshot[index].data["image"],
["image"]
是我得到错误的地方。我试着从另一个问题中使用.get("image")
,但没有成功。
我有这个:
late StreamSubscription<QuerySnapshot>subscription;
late List<DocumentSnapshot>snapshot;
CollectionReference collectionReference = FirebaseFirestore.instance.collection("Latest Post");
@override
void initState() {
subscription = collectionReference.snapshots().listen((datasnap) {
setState(() {
snapshot = datasnap.docs;
});
});
super.initState();
}
child: ListView.builder(
itemCount: snapshot.length,
itemBuilder: (context, index){
return Container(
width: 350.0,
child: Row(children: [
Expanded(
flex: 1,
child: Image.network(snapshot[index].data["image"],
但我收到了The operator '[]' isn't defined for the type 'Object? Function()'. Try defining the operator '[]'.
作为错误消息。
感谢您的帮助!
您可以使用.get
获取图像文件
Image.network(snapshot[index].get(["image"]),
或者这样,但当数据为null时,它会抛出错误。
Image.network((snapshot[index].data()! as Map)["image"]),
使用errorBuilder
进行
ListView.builder(
itemCount: snapshot.length,
itemBuilder: (context, index) {
final data = snapshot[index].data() as Map?;
if (data == null) return Text("got null");
return Container(
width: 350.0,
child: Row(children: [
Expanded(
flex: 1,
child: Image.network(
data["image"] ?? "",
errorBuilder: (context, error, stackTrace) =>
Text("got error on image loading"),
),
)
]));
})