【问题标题】:Flutter type 'List<dynamic>' is not a subtype of type 'List<Product>Flutter 类型“List<dynamic>”不是“List<Product>”类型的子类型
【发布时间】:2019-09-22 16:27:23
【问题描述】:

这是我的产品供应商:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../models/Product.dart';

class Products with ChangeNotifier {
  List<Product> _items = [];

  List<Product> get items {
    return [..._items];
  }

  Future<void> getProducts() async {
    try {
      final response =
          await Dio().get("https://jsonplaceholder.typicode.com/posts");
      final List<Product> body = response.data;
      _items = body;
      notifyListeners();
    } on DioError catch (e) {
      print(e);
    }
  }
}

然后,这是我的产品模型:

class Product {
  final String id;
  final String title;
  final String body;
  final String userId;

  Product({this.id, this.title, this.body, this.userId});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'],
      title: json['title'],
      body: json['body'],
      userId: json['userId'],
    );
  }
}

但是,在getProducts() 函数中,如果我将_items 分配给response.data,它会说

“列表”不是“列表”类型的子类型。

我在这里做错了吗?

【问题讨论】:

    标签: http flutter dart


    【解决方案1】:

    所以,实际上我必须安装Dio 包来检查您的代码出了什么问题。我对此进行了测试,现在可以 100% 正常工作

    class Products with ChangeNotifier {
      List<Product> _items = [];
    
      List<Product> get items {
        return [..._items];
      }
    
      Future<void> getProducts() async {
        try {
          final response = await Dio().get("https://jsonplaceholder.typicode.com/posts");
    
          // change this
          final List<dynamic> body = response.data;
          for (var data in body) {
            _items.add(Product.fromJson(data));
          }
        } on DioError catch (e) {
          print(e);
        }
      }
    }
    
    class Product {
      final int id; // change this
      final String title;
      final String body;
      final int userId; // and this
    
      Product({this.id, this.title, this.body, this.userId});
    
      factory Product.fromJson(Map<String, dynamic> json) {
        return Product(
          id: json['id'],
          title: json['title'],
          body: json['body'],
          userId: json['userId'],
        );
      }
    }
    

    【讨论】:

    • 如果我这样做,它不会让我分配:final List&lt;dynamic&gt; body = response.data; _items = body;。它总是说Unhandled Exception: type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Product&gt;'
    • 非常感谢!也感谢您指出愚蠢的错误。
    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-12-02
    • 2021-08-02
    • 2023-01-22
    相关资源
    最近更新 更多