如何将简单的FireBase数据放入ListView



如何将一些FireBase数据获取到ListView中?

以下代码成功地从FireBase返回产品列表:

final CollectionReference _products = FirebaseFirestore.instance.collection('products');
Future<List> getList() async {
QuerySnapshot querySnapshot = await _products.get();
final temp = querySnapshot.docs.map((doc) => doc.data()).toList();
return temp;
}

返回的数据如下所示:

[{quantity: 1.0, name: Greek Yogurt 🇬🇷, category: Dairy, priority: 0}, {quantity: 1.0, name: Watermelon 🍉, category: Produce, priority: 0}, {quantity: 1.0, name: Cinnamon 🍂, category: Spices, priority: 0}, {quantity: 4.0, name: Banana 🍌, priority: 0, category: Produce}, {quantity: 1.0, name: Heavy Cream 🐄, priority: 0, category: Dairy}]

我可以得到这些列&显示返回数据的文本窗口小部件:

return Column(
children: <Widget>[
const Text("FireBase Data"),
Text("${snapshot.data}"),
Text(snapshot.data?.length.toString() ?? '0'),
]
);

但每当我尝试使用ListView时,我都会被难住

有人能帮我把返回的数据放到ListView中吗

我相信它相对简单,我只是Flutter密集。。。

谢谢!

我不知道你想在ListView中显示什么,但我希望以下代码能帮助你实现你想要的:

if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Text("${snapshot.data[index]}");
},
);
}

您对ListView想要做什么非常模糊,但只要查看您的代码并尝试猜测您的意图,我就觉得这对我来说很有意义:

void main() async {
// I didn't know what to do with the below... so I commented it out.
// Widget listChild (snapshot){
//   return Column(children: <Widget>[
//     const Text("FireBase Data"),
//     Text("${snapshot.data}"),
//     Text(snapshot.data?.length.toString() ?? '0'),
//   ]);
// }
final CollectionReference _products = FirebaseFirestore.instance.collection('products');
Future<List> getList() async {
QuerySnapshot querySnapshot = await _products.get();
final temp = querySnapshot.docs.map((doc) => doc.data()).toList();
return temp;
}
List list = await getList();
// [{quantity: 1.0, name: Greek Yogurt 🇬🇷, category: Dairy, priority: 0}, {quantity: 1.0, name: Watermelon 🍉, category: Produce, priority: 0}, {quantity: 1.0, name: Cinnamon 🍂, category: Spices, priority: 0}, {quantity: 4.0, name: Banana 🍌, priority: 0, category: Produce}, {quantity: 1.0, name: Heavy Cream 🐄, priority: 0, category: Dairy}]
runApp(
MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Column(
children: [
Text(list[index]['quantity'].toString()),
Text(list[index]['name']),
Text(list[index]['category']),
Text(list[index]['priority'].toString()),
Divider(),
],
// This will give you a scrollable ListView of Columns,
// displaying all the data you got from Firebase.
);
}
),
),
),
);
}

如果这不是你想要的,请告诉我们是什么!🙂

最新更新