我尝试使用HTTP URL从Flutter Firebase获取数据,但是发生了此错误。 请帮我解决这个错误。 [错误:flutter / lib / ui / ui_dart_state.cc(166)]未处理的异常:类型'String'不是'index'的'int'类型的子类型 Products.fetchAndSetProducts 谢谢
Future<void> fetchAndSetProducts([bool filterByUser = false]) async {
final filterString = filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' :'';
var url = 'https://cowmilknew.firebaseio.com/products.json?auth=$authToken&$filterString';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
url =
'https://cowmilknew.firebaseio.com/RetailerWishlist/$userId.json?auth=$authToken';
final favoriteResponse = await http.get(url);
final favoriteData = json.decode(favoriteResponse.body);
final List<Product> loadedProducts = [];
extractedData.forEach((prodId, prodData) {
loadedProducts.add(Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
isFavorite: favoriteData == null ? false : favoriteData[prodId] ?? false,
imageUrl: prodData['imageUrl'],
));
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw (error);
}
}
@override
void didChangeDependencies() {
if (_isInit) {
setState(() {
_isLoading = true;
});
Provider.of<Products>(context,listen: false).fetchAndSetProducts().then((_) {
setState(() {
_isLoading = false;
});
});
}
_isInit = false;
super.didChangeDependencies();
}
答案 0 :(得分:0)
由于您没有提供完整的错误日志,所以我无法确切告诉您错误的位置,但是很显然您正在尝试将int传递给字符串,因此我猜测错误的原因可能在于价格: prodData ['price'] 这样做会将价格转换为整数吗?
price: prodData['price'].toString();