flutter - “产品”类型的值不能分配给“列表”类型的变量'
问题描述
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<List<Products>> getApiData() async {
var url = "https://gorest.co.in/public-api/products";
var response = await http.get(url);
var jsonString = response.body;
List<Products> products = productsFromJson(jsonString);
print(jsonString);
return products;
}
为什么它不起作用,[“产品”类型的值不能分配给“列表”类型的变量。尝试更改变量的类型,或将右侧类型转换为“列表”。;][1]
[1]: https://i.stack.imgur.com/MQCEP.png
json 到 dart 文件
“产品”类型的值不能分配给“列表”类型的变量。尝试改变变量的类型,dart(invalid_assignment)
Products productsFromJson(String str) =>
Products.fromJson(json.decode(str));
String productsToJson(Products data) => json.encode(data.toJson());
class Products {
Products({
this.code,
this.meta,
this.data,
});
int code;
Meta meta;
List<Datum> data;
factory Products.fromJson(Map<String, dynamic> json) => Products(
code: json["code"],
meta: Meta.fromJson(json["meta"]),
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"meta": meta.toJson(),
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.id,
this.name,
this.description,
this.image,
this.price,
this.discountAmount,
this.status,
this.categories,
});
int id;
String name;
String description;
String image;
String price;
String discountAmount;
bool status;
List<Category> categories;
解决方案
var url = "https://gorest.co.in/public-api/products";
var response = await http.get(url);
var jsonString = jsonDecode(response.body);
List<Products> products = jsonString.map((jsonMap) => Products.fromJson(jsonMap)).toList();
如果您需要将所有产品作为列表返回,您可以这样使用。
推荐阅读
- java - Java EOFException 问题 ObjectInputStream
- javascript - 使用 Ajax 发布带有变量的 JSON
- git - 使用“git rebase to”合并两个功能分支?
- azure-devops - 运行控制台应用程序作为输出测试结果的构建任务
- javascript - Laravel - 搜索时的 Ajax 重复数据
- python - 我们如何使用python中的变量从mysql数据库中获取特定行的详细信息
- javascript - 增加自定义对象的点击次数
- php - SessionHandlerInterface::write 和 SessionUpdateTimestampHandlerInterface::updateTimestamp 有什么区别?
- react-native - 如何使用带有参数的scrollTo函数是ListView中的目标而不是x和y?
- c# - wpf中的数据绑定与getter中的表达式