dart 未处理异常:类型“String”不是“index”获取数据的类型“int”的子类型

ttcibm8c  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(120)

我想把数据库中的产品(条目)id作为代码中对象的['id'],但我得到了这个错误codedatabase

Future<void> fetchAndSetProducts() async {
    final url =
        Uri.parse('https://flutter-update.firebaseio.com/products.json');
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      final List<Product> loadedProducts = [];
      extractedData.forEach((prodId, prodData) {
        loadedProducts.add(Product(
          id: prodId,
          title: prodData['title'],
          description: prodData['description'],
          price: prodData['price'],
          isFavorite: prodData['isFavorite'],
          imageUrl: prodData['imageUrl'],
        ));
      });
      _items = loadedProducts;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }
13z8s7eq

13z8s7eq1#

错误提示,您正在尝试访问索引为非整数值的字符串元素您是否可以共享从json文件接收的数据,并且打印prodData会更有帮助,因为它表明prodData似乎是字符串而不是您期望的Map类型

e7arh2l6

e7arh2l62#

试试这个:

Future<void> fetchAndSetProducts() async {
...
    extractedData.forEach((prodId, prodData) {
      loadedProducts.add(Product(
        id: prodId,
        title: prodData['title'] ?? 'Untitled',
        description: prodData['description'] ?? '',
        price: (prodData['price'] ?? 0).toDouble(),
        isFavorite: prodData['isFavorite'] ?? false,
        imageUrl: prodData['imageUrl'] ?? '',
      ));
    });
...
}

相关问题