firebase - 读取数据中的 Flutter Firebase 错误:输入“列表”' 不是类型 'Map 的子类型' 在类型转换中
问题描述
错误:发生异常。_CastError(类型 'List' 不是类型转换中类型 'Map<String, dynamic>' 的子类型)
我怎么解决这个问题??
编辑:'extractedData' 是 Map,我如何将其转换为 List 以将其添加到'final List loadedProducts = [];'?
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';
class ProductMain with ChangeNotifier{
final String idFood;
final String nameFood;
// ignore: non_constant_identifier_names
final String ImgUrl;
ProductMain({
@required this.idFood,
this.nameFood,
// ignore: non_constant_identifier_names
this.ImgUrl,
});
}
对于所需的帖子:“看起来您的帖子主要是代码;请添加更多详细信息。” “看起来你的帖子主要是代码;请添加更多细节。”
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:app/product_main_data.dart';
import 'package:http/http.dart' as http;
class ProductsMainPV with ChangeNotifier {
List<ProductMain> _items = [];
List<ProductMain> get items {
return [..._items];
}
ProductMain findById(String idFood) {
return _items.firstWhere((prod) => prod.idFood == idFood);
}
Future<void> fetchAndSetProducts() async {
const url =
'https://app.firebaseio.com/productList.json';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body);
final List<ProductMain> loadedProducts = [];
extractedData.forEach((product) {
print(product);
loadedProducts.add(ProductMain(
idFood: product,
nameFood: product['nameFood'],
ImgUrl: product['ImgUrl'],
));
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw (error);
}
}
void updateProduct(String id, ProductMain newProduct) {
final prodIndex = _items.indexWhere((prod) => prod.idFood == id);
if (prodIndex >= 0) {
_items[prodIndex] = newProduct;
notifyListeners();
} else {
print('...');
}
}
}
输出:
product is null
解决方案
我不确定这一点,因为您的问题不包含收到的响应结构。但是试试这个。
final extractedData = json.decode(response.body) as Map<String, dynamic>;
由于您要列出所有产品,因此它可能是项目列表。所以将其投射到 Map 是行不通的!
final extractedData = json.decode(response.body);
......
extractedData.forEach((product) {
print(product);
// Do Something!
}