json - Flutter json 需要一个“列表”类型的值',但有一个类型''
问题描述
嗨,我正在制作一个食谱应用程序,它显示食物的名称及其图像和成分,所以我制作了一个简单的主页,用于制作请求和一个类,它为我提供了我使用来自spooncular.com 的这个 url 的数据:
这是主要课程
import 'package:flutter/material.dart';
import 'package:flutter_application_1/recipes.dart';
import 'dart:convert' as cnv;
import 'package:http/http.dart' as http;
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_HomeScreen createState() => _HomeScreen();
}
class _HomeScreen extends State<HomeScreen> {
List<MissedIngredients>? modell;
@override
void initState() {
// TODO: implement initState
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Food recipe api'),
),
body: modell == null
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: ExpansionTile(
title: Text(modell![index].originalName.toString()),
children: [
Text(modell![index].name.toString()),
Container(
child:
Image.network('modell![index].image.toString()'),
)
],
),
);
},
itemCount: modell!.length),
);
}
Future<void> getData() async {
http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
print(res.body);
List<dynamic> body = cnv.jsonDecode(res.body)['missedIngredients'];
modell = body.map((dynamic item) => MissedIngredients.fromJson(item)).toList();
setState(() {});
}
}
这是我用 json 将它 mdae 到 dart 类网站的食谱类
class recipes {
List<Results> ?results;
int? offset;
int? number;
int? totalResults;
recipes({this.results, this.offset, this.number, this.totalResults});
recipes.fromJson(Map<String, dynamic> json) {
if (json['results'] != null) {
results = <Results>[];
json['results'].forEach((v) {
results!.add(new Results.fromJson(v));
});
}
offset = json['offset'];
number = json['number'];
totalResults = json['totalResults'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.results != null) {
data['results'] = this.results!.map((v) => v.toJson()).toList();
}
data['offset'] = this.offset;
data['number'] = this.number;
data['totalResults'] = this.totalResults;
return data;
}
}
class Results {
int? id;
int? usedIngredientCount;
int? missedIngredientCount;
List<MissedIngredients> ?missedIngredients;
int ?likes;
List<Null>? usedIngredients;
List<Null>? unusedIngredients;
String ?title;
String ?image;
String ?imageType;
Results(
{this.id,
this.usedIngredientCount,
this.missedIngredientCount,
this.missedIngredients,
this.likes,
this.usedIngredients,
this.unusedIngredients,
this.title,
this.image,
this.imageType});
Results.fromJson(Map<String, dynamic> json) {
id = json['id'];
usedIngredientCount = json['usedIngredientCount'];
missedIngredientCount = json['missedIngredientCount'];
if (json['missedIngredients'] != null) {
missedIngredients = <MissedIngredients>[];
json['missedIngredients'].forEach((v) {
missedIngredients!.add(new MissedIngredients.fromJson(v));
});
}
title = json['title'];
image = json['image'];
imageType = json['imageType'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['usedIngredientCount'] = this.usedIngredientCount;
data['missedIngredientCount'] = this.missedIngredientCount;
if (this.missedIngredients != null) {
data['missedIngredients'] =
this.missedIngredients!.map((v) => v.toJson()).toList();
}
data['likes'] = this.likes;
data['title'] = this.title;
data['image'] = this.image;
data['imageType'] = this.imageType;
return data;
}
}
class MissedIngredients {
int ? id;
double? amount;
String ?unit;
String ?unitLong;
String ?unitShort;
String? aisle;
String? name;
String? original;
String? originalString;
String? originalName;
List<String> ?metaInformation;
List<String>? meta;
String ?image;
String? extendedName;
MissedIngredients(
{this.id,
this.amount,
this.unit,
this.unitLong,
this.unitShort,
this.aisle,
this.name,
this.original,
this.originalString,
this.originalName,
this.metaInformation,
this.meta,
this.image,
this.extendedName});
MissedIngredients.fromJson(Map<String, dynamic> json) {
id = json['id'];
amount = json['amount'];
unit = json['unit'];
unitLong = json['unitLong'];
unitShort = json['unitShort'];
aisle = json['aisle'];
name = json['name'];
original = json['original'];
originalString = json['originalString'];
originalName = json['originalName'];
metaInformation = json['metaInformation'].cast<String>();
meta = json['meta'].cast<String>();
image = json['image'];
extendedName = json['extendedName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['amount'] = this.amount;
data['unit'] = this.unit;
data['unitLong'] = this.unitLong;
data['unitShort'] = this.unitShort;
data['aisle'] = this.aisle;
data['name'] = this.name;
data['original'] = this.original;
data['originalString'] = this.originalString;
data['originalName'] = this.originalName;
data['metaInformation'] = this.metaInformation;
data['meta'] = this.meta;
data['image'] = this.image;
data['extendedName'] = this.extendedName;
return data;
}
}
注意:当我尝试使用 Results 类(如标题或图像)时,它可以工作,但是当我尝试使用missingredants 类时,它给了我这个错误 Expected a value of type 'List',但如果你得到一个类型为'Null'的值想了解更多信息,请向我提问,谢谢!
解决方案
在您的情况下使用以下方法,
Future<void> getData() async {
http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
print(res.body);
var jsonData = cnv.jsonDecode(res.body);
modell = jsonData['results'][0]['missedIngredients'].map((dynamic item) => MissedIngredients.fromJson(item)).toList();
setState(() {});
}
当您的“结果”列表中有多个数据时,您可以在 resultList 数组中找到“missedIngredients”列表,
Future<void> getData() async {
http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
print(res.body);
var jsonData = cnv.jsonDecode(res.body);
List<Results> resultList = jsonData['results'].map(
(jsonElement) => Results.fromJson(jsonElement)
).toList();
print(resultList[0].missedIngredients.length.toString());
}
推荐阅读
- javascript - POST 请求循环访问 8 个不同的 url
- laravel - 通过 nginx 限制 laravel 路由
- php - curl 中的 API 密钥
- swift - 有没有办法消除 SwiftUI 中填充的外边缘?
- sql - 如何聚合维度变化缓慢的数据
- python - 在 MAP 函数中使用 for 循环
- sql - 使用 EXISTS 指令是否改进了这个查询
- python - 是否有任何选项可以检查 URL 是否有效?在将它传递给 scrapy 中的下一个函数之前,Python
- spring - 使用 @EventListener 的 Spring ExitCodeEvent 不起作用
- python - 如何将其更改为超链接?不和谐.py