简体   繁体   English

如何通过在 Flutter 中以 JSON_Serializable 方式遍历 JSON 数组来填充 GridView?

[英]How do I populate a GridView by traversing a JSON array in Flutter the JSON_Serializable way?

I'm trying to parse an array of JSON Objects to populate a GridView in Flutter.我正在尝试解析一组 JSON 对象以填充 Flutter 中的GridView So far, I can only get a single object, but can't traverse the whole array of objects.到目前为止,我只能获取单个对象,但无法遍历整个对象数组。

JSON String: A list of Beef recipe objects within 'beef' array. JSON 字符串: “牛肉”数组中的牛肉食谱对象列表。

My code:我的代码:

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']);
  }
}

Sample object traversal path:示例对象遍历路径:

{"meals":[{"strMeal":"Beef and Mustard Pie","strMealThumb":"https:\\/\\/www.themealdb.com\\/images\\/media\\/meals\\/sytuqu1511553755.jpg","idMeal":"52874"}, {object1}, {object2}]}

What I'm getting:我得到了什么:

{"strMeal":"Beef and Mustard Pie","strMealThumb":"https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal":"52874"} {"strMeal":"牛肉芥末派","strMealThumb":"https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal":"52874"}

How do I get all objects in the array and inflate the GridView widget?如何获取数组中的所有对象并扩充 GridView 小部件?

import 'dart:convert';

// First you should create a model to represent a meal
class Meal {
  
  // Place all the meal properties here
  final String strMeal;
  final String strMealThumb;
  final String idMeal;

  // Create a constructor that accepts all properties. They can be required or not
  Meal({
    required this.strMeal,
    required this.strMealThumb,
    required this.idMeal,
  });

  // Create a method (or factory constructor to populate the object based on a json input)
  factory Meal.fromJson(Map<String, dynamic> json) => Meal(
        strMeal: json['strMeal'],
        strMealThumb: json['strMealThumb'],
        idMeal: json['idMeal'],
      );
  
  String toString() {
    return 'strMeal: $strMeal, strMealThumb: $strMealThumb, idMeal: $idMeal';
  }
}

/// Then you should create another object to represent your response
/// It holds a list of meals that'll be populated by your API response

class YourAPIResponse {
  final List<Meal> meals;

  YourAPIResponse({required this.meals});

  factory YourAPIResponse.fromJson(Map<String, dynamic> json) =>
      YourAPIResponse(
        meals: List<Meal>.from(
          json['meals'].map((meal) => Meal.fromJson(meal)),
        ),
      );
}

void main() {
  // Test data: This will be your API response
  String jsonString = '{"meals": [{"strMeal": "Beef and Mustard Pie","strMealThumb": "https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal": "52874"}]}';
  
  final apiResponse = YourAPIResponse.fromJson(json.decode(jsonString));
  
  // Your meals list
  // You can use this to populate the gridview
  print(apiResponse.meals);
}

Try something like:尝试类似:

...
   return jsonDecode(mealsData.body)['meals'].map((meal) => Meal.fromJson(meal)).toList();
...

class Meal {
  final String? id, meal;

  Meal({required this.id, required this.meal});

  factory Meal.fromJson(Map<String, dynamic> json) {
    return Meal(
        id: json['idMeal'], meal: json['strMeal']);
  }
}

This iterates the meals in your response body and maps them to a List of Meal s.这将迭代您的响应正文中的Meal并将它们映射到一个 List of Meal s。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 json_serializable flutter 中将 int 时间戳转换为 DateTime - How to convert int timestamp to DateTime in json_serializable flutter 如何在标记中使用json_serializable在GoogleMap中使用它们? - How to use json_serializable in flutter with markers to use them in a GoogleMap? 如何在继承类上生成 Json_Serializable Dart (Flutter)? - How to Generate Json_Serializable Dart (Flutter) on Inheritance class? Flutter:json_serializable 1 =&gt; true,0 =&gt; false - Flutter: json_serializable 1 => true, 0 => false flutter json_serializable 丢失文件 - flutter json_serializable missing file Flutter:将 50+ model 类转换为支持 json_serializable 的快速方法 - Flutter : Quick way to convert 50+ model classes to supports json_serializable Flutter-来自Json的json_serializable:方法&#39;[]&#39;在null上调用 - Flutter - json_serializable fromJson: The method '[]' was called on null 错误的 state json_serializable package 与 flutter 的意外诊断 - Bad state Unexpected diagnostics on json_serializable package with flutter Flutter - 使用json_serializable反序列化firebase_messagin通知 - Flutter - Deserialize firebase_messagin notification using json_serializable Dart/Flutter:build_value 与 json_serializable - Dart/Flutter: build_value vs json_serializable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM