Flutter类型“ List <dynamic>”不是类型“ List <Product>”的子类型

时间:2019-09-22 16:27:23

标签: http flutter dart

这是我的产品提供商:

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,则会显示

  

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

我在这里做错什么了吗?

1 个答案:

答案 0 :(得分: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'],
    );
  }
}