【问题标题】:Flutter/Dart - 'List<dynamic>' is not a subtype of type 'List<Product>'Flutter/Dart - “List<dynamic>”不是“List<Product>”类型的子类型
【发布时间】: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

标签: flutter dart dynamic


【解决方案1】:

问题是你正在尝试做这个作业

_item = loadedProducts;

其中_item 的类型为List&lt;Product&gt;loadedProductsList&lt;dynamic&gt;

尝试像这样初始化loadedProducts

// final loadedProducts = [];        // Remove this line
List<Product> loadedProducts = [];   // Use this instead

【讨论】:

  • @PrabithaNair 如果这个答案是您问题的最佳解决方案,您可以mark it as accepted
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 2020-11-15
相关资源
最近更新 更多