【发布时间】:2020-06-06 03:12:47
【问题描述】:
我正在解码从 firebase 获得的 JSON 对象。但我在对 Map 的响应进行类型转换时收到如下错误。
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未处理的异常:“List”类型不是“List”类型的子类型
产品型号
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product(
{this.isFavorite = false,
@required this.id,
@required this.title,
@required this.description,
@required this.price,
@required this.imageUrl});
void toggleFavoriteStatus() {
isFavorite = !isFavorite;
notifyListeners();
}
}
Future<void> fetchAndSetProducts() async {
const url = 'https://myshop-*****.firebaseio.com/products.json';
try {
final response = await http.get(url);
final loadedProducts = [];
print(response.body);
final extractedData =
json.decode(response.body) as Map<String, dynamic>;
extractedData.forEach((prodId, value) {
loadedProducts.add(Product(
id: prodId,
description: value['description'],
title: value['title'],
price: value['price'],
imageUrl: value['imageUrl'],
isFavorite: value['isFavorite']));
});
_item = loadedProducts;
notifyListeners();
} catch (error) {
throw (error);
}
}
我从 Firebase 得到的回应是
{
"-M0YDsU3HT89_wzAx1GQ": {
"description": "shirt",
"imageUrl": "https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
"isFavorite": false,
"price": 79,
"title": "shirt"
}
}
【问题讨论】:
-
您能否为您的问题添加更多上下文代码,我们看不到您执行了哪些代码来使您的应用程序崩溃?谢谢
-
我已经包含了调用url的代码。
-
_item的类型是什么? -
您正在尝试
forEach地图,而您从firebase 得到的答案也不是List