gpt4 book ai didi

http - Flutter 类型 'List' 不是“List”类型的子类型

转载 作者:行者123 更新时间:2023-12-02 03:09:33 28 4
gpt4 key购买 nike

这是我的产品提供商:

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

'List' is not a subtype of type 'List'.

我在这里做错了什么吗?

最佳答案

所以,实际上我必须安装 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'],
);
}
}

关于http - Flutter 类型 'List<dynamic>' 不是“List<Product>”类型的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58051200/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com