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;
}为什么它不能工作,类型'Products‘的值不能分配给'List’类型的变量。尝试更改变量的类型,或将右侧类型转换为“List”。
[1]: https://i.stack.imgur.com/MQCEP.pngjson到dart文件
类型'Products‘的值不能分配给'List’类型的变量。尝试更改变量的类型,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;发布于 2021-01-14 09:30:45
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();如果您需要将所有产品作为列表返回,您可以这样使用。
发布于 2021-01-14 08:17:57
您为产品创建了一个Modle类,因此productsFromJson(jsonString)返回一个产品响应。但是您尝试将API响应放入List变量,然后它会导致一个错误。
通过下面的代码更改您的API调用,它将很好地工作。
Future<Products> getApiData() async {
var url = "https://gorest.co.in/public-api/products";
var response = await http.get(url);
var jsonString = response.body;
Products products = productsFromJson(jsonString);
print(jsonString);
return products;
}https://stackoverflow.com/questions/65715175
复制相似问题