[英]How can I add new item in a list?
class Restaurants with ChangeNotifier {
List<Restaurant> _restaurants = [];
List<Restaurant> get getRestaurants1 {
return [..._restaurants];
}
Future<void> fetchAndSetRestaurants() async {
List<Restaurant> tempRestaurants = [];
try {
List<RestaurantItems> restItems = [];
List<Reviews> reviews = [];
await FirebaseFirestore.instance.collection('restaurants').get().then(
(restaurants) => restaurants.docs.forEach(
(restaurantData) async {
if (restaurantData.id == null) {
print('no id error');
}
print('restaurant Id:');
print(restaurantData.id);
final Map<String, dynamic> restaurant = restaurantData.data();
print(restaurant);
await FirebaseFirestore.instance // Restaurant Items
.collection('restaurants')
.doc(restaurantData.id)
.collection('restaurantItems')
.get()
.then(
(firestoreRestaurantItems) {
firestoreRestaurantItems.docs.forEach(
(restItemData) {
print(restItemData.data());
final Map<String, dynamic> restItem =
restItemData.data();
print('before:');
print(restItem['price'].runtimeType);
final RestaurantItems newRestaurantItem =
RestaurantItems(
id: restItemData.id,
description: restItem['description'],
//imageUrl: restItem['imageUrl'],
isVeg: restItem['isVeg'],
name: restItem['name'],
price: restItem['price'].toDouble(),
quantity: restItem['quantity'],
);
print('After:');
print(newRestaurantItem.name);
if (newRestaurantItem == null) {
print('fail');
}
restItems.add(newRestaurantItem);
},
);
},
);
await FirebaseFirestore.instance // Restaurant Items
.collection('restaurants')
.doc(restaurantData.id)
.collection('reviews')
.get()
.then(
(firestorReviews) {
firestorReviews.docs.forEach(
(reviewData) {
final Map<String, dynamic> review = reviewData.data();
print('before:');
print(reviewData['text']);
final Reviews newReview = Reviews(
id: reviewData.id,
rating: review['rating'],
description: review['description'],
text: review['text']);
print('after');
print(newReview.text);
reviews.add(newReview);
},
);
},
);
final strings = List<String>.from(restaurant['cuisine']);
print(strings.runtimeType);
final newRestaurant = Restaurant(
id: restaurantData.id,
name: restaurant['name'],
description: restaurant['description'],
cuisine: List<String>.from(restaurant['cuisine']),
imageUrl: restaurant['imageUrl'],
isAvailable: restaurant['isAvailable'],
isFavourite: restaurant['isFavourite'],
pickupTime: restaurant['pickupTime'].toDate(),
stars: restaurant['stars'].toDouble(),
location: Location(
address: restaurant['location']['address'],
city: restaurant['location']['city'],
latitude: restaurant['location']['latitude'],
longitude: restaurant['location']['longitude'],
zipcode: restaurant['location']['zipcode'],
locality: restaurant['location']['locality'],
),
items: restItems,
reviews: reviews,
);
print(newRestaurant.name);
tempRestaurants.add(newRestaurant);
print('temp:${tempRestaurants.length}');
_restaurants.add(newRestaurant);
// print('final:${_restaurants.length}');
},
),
);
print('_restaurants: ${_restaurants[0].imageUrl}');
notifyListeners();
} catch (error) {
print('error in fetchAndSetRestaurants');
throw error;
}
}
}
我正在尝试从 firestore 检索餐厅数据,但是当我将新餐厅项目添加到我的主列表 (_restaurants) 时,它给了我以下错误:
flutter:fetchAndSetRestaurants [VERBOSE-2:ui_dart_state.cc(177)] 中的错误未处理异常:RangeError(索引):无效值:有效值范围为空:0
即使在其中添加了newRestaurant之后, _restaurants变量似乎也是空的。
您应该使用async-await构造,因为您正在尝试在数据仍在获取时检索项目。
https://dart.dev/codelabs/async-await
像那样:
final restaurants = await FirebaseFirestore.instance.collection('restaurants').get();
for (final restaurant in restaurants.docs) {
final items = FirebaseFirestore.instance.collection('restaurants')
.doc(restaurant.id)
.collection('restaurantItems')
.get();
.......
}
接着
if (_restaurants.isNotEmpty) {
print('_restaurants: ${_restaurants[0].imageUrl}');
}
notifyListeners();
和两件重要的事情:
这个结构不好
我认为有必要拆分从 FireStore 请求数据的方法,就像那样
希望能帮助到你:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.