[英]get list from fireStore in flutter app with indexes
我正在尝试从 firestore 获取列表,但我遇到了索引问题。
这是列表上普通项目的结构,每个对象都包含一个项目列表:
class RestaurantFoodList {
final String id ;
final String title;
List <RestaurantitemList> items ;
final String imageUrl;
RestaurantFoodList({this.id,this.title,this.items,this.imageUrl});
}
这是项目本身的结构:
class RestaurantitemList {
final String id ;
final String title ;
final String imageUrl ;
final String description ;
final int price ;
final int shippingPrice;
List<Checkbox> cheker;
RestaurantitemList({this.id,this.title,this.imageUrl,this.description,this.price,this.shippingPrice,this.cheker});
}
这就是我在 firestore 中添加对象的方式:
Future<void> addLitem(RestaurantFoodList foodList, RestaurantitemList itemList) async {
final _fireStore = Firestore.instance;
_fireStore.collection('restaurant').add({
'title': foodList.title,
'imageUrl': foodList.imageUrl,
'items': [
{
'id': itemList.id,
'title': itemList.title,
'imageUrl': itemList.imageUrl,
}
],
});
}
这是我的 firestore 数据,我的问题是如何正确获取所有列表及其项目,我试过这个,但没有用:
Future<void> fetchAndSetList() async {
final List<RestaurantFoodList> loadedList = [];
await Firestore.instance.collection("restaurant").getDocuments().then(
(QuerySnapshot snapshot) => snapshot.documents.forEach(
(f) => loadedList.insert(
0,
RestaurantFoodList(
id: f.data['id'],
imageUrl: f.data['imageUrl'],
title: f.data['title'],
items: [f.data['items']]
),
),
),
);
notifyListeners();
_restaurantItems[3].itemsList = loadedList;
}
注意:如果我编写另一种方法来获取项目,我必须编写
items: loadedItem.add(RestaurantitemList(
id : f.data['items'][0]['id']
))
但我想获得所有项目列表而不仅仅是一个项目,所以这里的索引方法我认为这是一个错误。
我已经删除了第一个答案,我正在添加一个新答案(一旦你看到它就会编辑掉这一行)。
所以,你的fetchAndSetList
函数存在一些问题,我重写了它:
Future < void > fetchAndSetList() async {
final List < RestaurantFoodList > loadedList = [];
final List < RestaurantitemList > itemList = [];
await Firestore.instance.collection("restaurant").getDocuments().then(
(QuerySnapshot snapshot) => snapshot.documents.forEach((f) => {
itemList = [];
f.data['items'].forEach((i) =>
itemList.add(RestaurantitemList(
id: i.id,
title: i.title,
imageUrl i.imageUrl
// you might need to add all fields here, even if they are null
)
);
loadedList.add(RestaurantFoodList(
id: f.data['id'],
imageUrl: f.data['imageUrl'],
title: f.data['title'],
items: itemList
))
});
);
notifyListeners();
}
我改变了什么?
itemList
变量的列表, RestaurantitemList
,你将添加到您的最终loadedList
;RestaurantitemList
对象填充 itemList,我还添加了一条注释,说明您应该添加您已映射到RestaurantitemList
对象的所有字段;loadedList.insert
更改为loadedList.add
,因此您不必担心将记录添加到哪个位置。注意:这是未经测试的,但它应该可以解决存在的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.