我正在嘗試執行 http.get 請求來獲取我已經發布的資料(作業完美)到 firebase(實時存盤)但是當我呼叫獲取資料的方法時,它會拋出_TypeError 錯誤(型別'int'不是“雙”型別的子型別)請注意,我正在使用提供者狀態管理
以下是用于感染我的資料的方法
Future<void> getAndSetProducts() async {
const url = 'https://shop-12901-default-rtdb.firebaseio.com/products.json';
try {
final response = await http.get(Uri.parse(url));
var extractedResponse =
json.decode(response.body) as Map<String, dynamic>;
List<Product> loadedProducts = [];
extractedResponse.forEach((prodId, product) {
loadedProducts.add(
Product(
id: prodId,
title: product['title'],
price: product['price'], //-Sure the error is from here but not sure of how to resolve it-
imageUrl: product['imageUrl'],
description: product['description'],
isFavorite: product['isFavorite'],
),
);
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw error; //--------TypeError (type 'int' is not a subtype of type 'double')-------
}
}
下面也是我呼叫上面的方法來執行其任務的方法
@override
void didChangeDependencies() {
if (_isInit) {
setState(() {
isLoading = true;
});
try {
Provider.of<Products>(context).getAndSetProducts().then((_) {
setState(() {
isLoading = false;
});
});
} catch (error) {
print(error);
}
}
_isInit = false;
super.didChangeDependencies();
}
uj5u.com熱心網友回復:
添加您的Product型號代碼。可能您已經double在模型中宣告了價格型別,但您正在傳遞int給它。使用轉換int為雙精度product['price'].toDouble()
uj5u.com熱心網友回復:
您可以使用 toDouble(); 代碼后的函式(例如:-> product['price'].toDouble)或者您可以使用 double.parse(value); 代碼后的函式(例如:-> double.parse(product['price']);)
uj5u.com熱心網友回復:
嘗試以 a 獲取價格,num然后將其決議為double.
Future<void> getAndSetProducts() async {
const url = 'https://shop-12901-default-rtdb.firebaseio.com/products.json';
try {
final response = await http.get(Uri.parse(url));
var extractedResponse =
json.decode(response.body) as Map<String, dynamic>;
List<Product> loadedProducts = [];
extractedResponse.forEach((prodId, product) {
loadedProducts.add(
Product(
id: prodId,
title: product['title'],
price: (product['price'] as num).toDouble(), //Try this
imageUrl: product['imageUrl'],
description: product['description'],
isFavorite: product['isFavorite'],
),
);
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw error; //--------TypeError (type 'int' is not a subtype of type 'double')-------
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449590.html
