繁体   English   中英

Flutter - 如何基于相同的值在单个 Json 文件中显示来自 2 个对象的数据

[英]Flutter - How to show data from 2 objects in single Json file based on the same value

我有 JSON 文件,其中包含食物和指令两个对象:
这是post.json

{
    "food": [
       {
           "id": "0001",
           "name": "Cake",
           "description":
              {
                "batter":
                   [ { "id": "instruction_1002", "type": "Chocolate" } ]
              }
       },
       {
           "id": "0002",
           "name": "Raised",
           "description":
             {
               "batter":
                [ { "id": "instruction_1003", "type": "Blueberry" } ]
             }
       }
    ],
    "instruction": [
       {
         "category": "instruction_1002",
         "content": "abc1234"
       },
       {
         "category": "instruction_1002",
         "content": "another food instruction"
       },
       {
         "category": "instruction_1003",
         "content": "def56789"
       },
       {
         "category": "instruction_1003",
         "content": "def56789"
       }
    ]
}

我希望当点击食物的名称时,它会根据与其匹配的类别显示说明内容。
示例:当 Cake 面糊 id = instruction.category 时,Cake 的指令内容为 abc1234
在此处输入图像描述

下面是 model 文件

class Post {
    List<Food>? food;
    List<Instruction>? instruction;
    Post({this.food, this.instruction});

    Post.fromJson(Map<String, dynamic> json) {
        if (json['food'] != null) {
            food = <Food>[];
            json['food'].forEach((v) {
                food!.add(new Food.fromJson(v));
            });
        }
        if (json['instruction'] != null) {
            instruction = <Instruction>[];
            json['instruction'].forEach((v) {
                instruction!.add(new Instruction.fromJson(v));
            });
        }
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.food != null) {
            data['food'] = this.food!.map((v) => v.toJson()).toList();
        }
        if (this.instruction != null) {
          data['instruction'] = this.instruction!.map((v) => v.toJson()).toList();
        }
        return data;
    }
}

class Food {
  String? id;
  String? name;
  Description? description;

  Food({this.id, this.name, this.description});
  Food.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    description = json['description'] != null ? new Description.fromJson(json['description']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    if (this.description != null) {
        data['description'] = this.description!.toJson();
    }
    return data;
  }
}

class Description {
    Description({
    List<Batter>? batter,
}) {
    _batter = batter;
}

Description.fromJson(dynamic json) {
    if (json['batter'] != null) {
        _batter = [];
        json['batter'].forEach((v) {
            _batter?.add(Batter.fromJson(v));
        });
    }
}
List<Batter>? _batter;
List<Batter>? get batter => _batter;

Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    if (_batter != null) {
       map['batter'] = _batter?.map((v) => v.toJson()).toList();
    }
    return map;
    }
}

class Batter {
  Batter({
    String? id,
    String? type,
  }) {
    _id = id;
    _type = type;
  }

  Batter.fromJson(dynamic json) {
    _id = json['id'];
    _type = json['type'];
  }
  String? _id;
  String? _type;

  String? get id => _id;
  String? get type => _type;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['id'] = _id;
    map['type'] = _type;
    return map;
  }
}

class Instruction {
  Instruction({
    String? category,
    String? content,
  }) {
    _category = category;
    _content = content;
  }

  Instruction.fromJson(dynamic json) {
    _category = json['category'];
    _content = json['content'];
  }
    String? _category;
    String? _content;

    String? get category => _category;
    String? get content => _content;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['category'] = _category;
    map['content'] = _content;
    return map;
  }
}

这是主文件:

import 'package:flutter/material.dart';
import '../model/post.dart';
import 'package:flutter/services.dart';
import 'dart:convert';

void main() {
  runApp(const MyApp());
}

Future<Post> getList() async {
  final getResponse = await rootBundle.loadString('assest/post.json');
  var data = jsonDecode(getResponse);
  return Post.fromJson(data);
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Post'),),
      body: Column(
        children: [
          Expanded(
            child: FutureBuilder<Post>(
              future: getList(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  var getText = snapshot.data!.food;
                  return SingleChildScrollView(
                    child: Wrap(
                      children: [
                        for (final word in getText!)
                          GestureDetector(
                            child: Text(word.name.toString()),
                            onTap: () {
                              Navigator.push( context, MaterialPageRoute(builder: (context) => foodDetail(food: word)) );
                            },
                          ),
                      ],
                    ),
                  );
                } else {
                  return Text('Loading');
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}

在这个主文件中,我可以列出所有的食物名称,但之后如何在 foodDetail 页面中继续? 请帮忙。

在您的 onTap 中找到说明:

List<Instruction> instructions = myPost.instruction?.where((element) => element.category == selectedFood.description?.batter?[0].id).toList();

将指令也作为参数传递给 foodDetail

foodDetail(food: word, instruction: instructions)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM