Flutter json api问题,部分数据不监听



大家好,我有一个小项目与扑动。试着从https://www.themealdb.com/上列出膳食清单。我想列出api中的膳食。到目前为止还好,但主要问题是有些食物列出了一些不是。

例如,牛肉类别不听,给我这个错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)]未处理的异常:类型'Null'不是'String'类型的子类型

但是素食主义者在倾听。

screen

class _MealScreenState extends State<MealScreen> {
List<Meal> mealsIn = [];
Future<bool> getMealInside() async {
Uri uri = Uri.parse(
'https://www.themealdb.com/api/json/v1/1/search.php?s=${widget.names}');
final response = await http.get(uri);
if (response.statusCode == 200) {
final result = mealsJsonFromJson(response.body);
mealsIn = result.meals;
setState(() {});
return true;
} else {
return false;
}
}
@override
void initState() {
super.initState();
getMealInside();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.names),
),
body: ListView.separated(
itemBuilder: (context, index) {
final mealsOut = mealsIn[index];
return ListTile(
title: Text(mealsOut.strMeal != null
? mealsOut.strMeal.toString()
: 'Loading'),
leading: Image.network(mealsOut.strMealThumb),
);
},
separatorBuilder: (context, index) => Divider(),
itemCount: mealsIn.length
),
);
}
}

模型页面:

import 'dart:convert';
MealData mealDataFromJson(String str) => MealData.fromJson(json.decode(str));
String mealDataToJson(MealData data) => json.encode(data.toJson());
class MealData {
MealData({
required this.categories,
});
List<Category> categories;
factory MealData.fromJson(Map<String, dynamic> json) => MealData(
categories: List<Category>.from(json["categories"].map((x) => Category.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"categories": List<dynamic>.from(categories.map((x) => x.toJson())),
};
class Category {
Category({
required this.idCategory,
required this.strCategory,
required this.strCategoryThumb,
required this.strCategoryDescription,
});
String idCategory;
String strCategory;
String strCategoryThumb;
String strCategoryDescription;
factory Category.fromJson(Map<String, dynamic> json) => Category(
idCategory: json["idCategory"],
strCategory: json["strCategory"],
strCategoryThumb: json["strCategoryThumb"],
strCategoryDescription: json["strCategoryDescription"],
);
Map<String, dynamic> toJson() => {
"idCategory": idCategory,
"strCategory": strCategory,
"strCategoryThumb": strCategoryThumb,
"strCategoryDescription": strCategoryDescription,
};
}

牛肉素食

您必须为每个键添加null检查:对于Categoryclass

factory Category.fromJson(Map<String, dynamic> json) => Category(
idCategory: json["idCategory"] ?? "",
strCategory: json["strCategory"] ?? "",
strCategoryThumb: json["strCategoryThumb"] ?? "",
strCategoryDescription: json["strCategoryDescription"] ?? "",
);

最新更新