【发布时间】:2021-09-22 14:05:58
【问题描述】:
我正在尝试解析 JSON 对象数组以填充 Flutter 中的 GridView。 到目前为止,我只能获取单个对象,而无法遍历整个对象数组。
JSON 字符串:A list of Beef recipe objects within 'beef' array.
我的代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class SpecificCategoryPage extends StatefulWidget {
late final String category;
SpecificCategoryPage({Key? key, required this.category}) : super(key: key);
@override
_SpecificCategoryPageState createState() => _SpecificCategoryPageState();
}
class _SpecificCategoryPageState extends State<SpecificCategoryPage> {
late Future<Meal> meals;
late List<Widget> mealCards;
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<Meal>(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
'Truest\nId: ${snapshot.data!.id}. ${snapshot.data!.meal}');
} else {
return Text('${snapshot.error}');
}
// Be default, show a loading spinner.
return CircularProgressIndicator();
},
future: meals,
),
);
}
@override
void initState() {
super.initState();
meals = _fetchMeals();
}
Future<Meal> _fetchMeals() async {
final http.Response mealsData = await http.get(
Uri.parse('https://www.themealdb.com/api/json/v1/1/filter.php?c=Beef'));
if (mealsData.statusCode == 200)
return Meal.fromJson(jsonDecode(mealsData.body));
else
throw Exception('Failed to load meals');
}
class Meal {
final String? id, meal;
Meal({required this.id, required this.meal});
factory Meal.fromJson(Map<String, dynamic> json) {
return Meal(
id: json['meals'][0]['idMeal'], meal: json['meals'][0]['strMeal']);
}
}
示例对象遍历路径:
{"meals":[{"strMeal":"Beef and Mustard Pie","strMealThumb":"https:\/\/www.themealdb.com\/images\/media\/meals\/sytuqu1511553755.jpg","idMeal":"52874"}, {object1}, {object2}]}
我得到了什么:
{"strMeal":"牛肉和芥末 Pie","strMealThumb":"https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal":"52874"}
如何获取数组中的所有对象并膨胀 GridView 小部件?
【问题讨论】:
-
为了将来 Json 解析到 dart 我推荐使用这个网站:app.quicktype.io
标签: json flutter dart serializable mobile-development