【问题标题】:Accessing quicktype JSON object in flutter在flutter中访问quicktype JSON对象
【发布时间】:2020-10-08 22:17:50
【问题描述】:

我有一个 JSON 字符串,它使用 quicktype 中生成的代码映射到“Pax”的一个实例中。 Quicktype 生成了大约 4000 行代码映射这个,所以我很高兴并且相信它在某种程度上可以工作。我现在想打印这个海量数据的一小部分作为开​​始。这是一个位于 pax.instructions.id 的字符串。

final String paxRaw = response.body;
final Pax xa = paxFromJson(paxRaw);
    import 'dart:convert';
    
    Pax paxFromJson(String str) => Pax.fromJson(json.decode(str));
    
    String paxToJson(Pwa data) => json.encode(data.toJson());
    
    class Pax {
      Pax({
        this.greeting,
        this.instructions,
      });
    
      String greeting;
      List<Instruction> instructions;
    
      factory Pax.fromRawJson(String str) => Pax.fromJson(json.decode(str));
    
      String toRawJson() => json.encode(toJson());
    
      factory Pax.fromJson(Map<String, dynamic> json) => Pax(
        greeting: json["greeting"] == null ? null : json["greeting"],
        instructions: json["instructions"] == null ? null : List<Instruction>.from(json["instructions"].map((x) => Instruction.fromJson(x))),
      );
    
      Map<String, dynamic> toJson() => {
        "greeting": greeting == null ? null : greeting,
        "instructions": instructions == null ? null : List<dynamic>.from(instructions.map((x) => x.toJson())),
      };
    }

我想访问列表 instructions 中名为 id 的数据成员。

print(xa);

返回控制台:

I/flutter ( 4535): Instance of 'Pax'

我知道指令是一个列表,但是如何访问该列表中称为 id 的字符串?我最好的猜测是 print(xa.instructions&lt;id&gt;); 但它不起作用。显然已经构建了一些东西,但我不知道如何在调试级别(在 android studio 中)检查“xa”。有助于指导。

更新,还是不行

  Future<Pax> _futurePax;

  Future<Pax> getPax() async {
    debugPrint("getPax start");
[...]
    http.Response response = await http.get(baseUri);
    debugPrint('Response status: ${response.statusCode}');
    debugPrint(response.body);
    return Pax.fromJson(json.decode(response.body));
  }
  @override
  void initState(){
    super.initState();
    setState(() {
      _futurePax = getPax();
    });
  }
Container (
                child: FutureBuilder<Pax> (
                    future: _futurePax,
                    builder: (context, snapshot) {
                      debugPrint("Futurebuilder<Pax> buildpart");
                      debugPrint("Test snapshot content: ${snapshot.data.toString()}");
                      debugPrint("Test snapshot error: ${snapshot.error}");
                      debugPrint("Test snapshot has data (bool): ${snapshot.hasData}");
                      debugPrint(snapshot.data.instructions[0].id);
                      return Text("Snap: ${snapshot.data.instructions[0].id}");
                    }
              ),
              ),

控制台:

Syncing files to device sdk gphone x86...
I/flutter ( 5126): Futurebuilder<Pax> buildpart
I/flutter ( 5126): Test snapshot content: Instance of 'Pax'
I/flutter ( 5126): Test snapshot error: null
I/flutter ( 5126): Test snapshot has data (bool): true

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<Pax>(dirty, state: _FutureBuilderState<Pax>#a2168):
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

【问题讨论】:

标签: json parsing flutter quicktype


【解决方案1】:

greetingsinstructionsquicktype 默认显示的“样本”json 的一部分。

json you shared 完全不同,它不包含 instructions 属性,因此永远找不到它。

【讨论】:

    【解决方案2】:
    Future<Pax> getPax() async {
    ....//call function body
    print(response.body)
    return Pax.fromJson(json.decode(response.body));
    }
    

    然后,您可以从构建器方法中检索任何此类字段。在你的构建方法中创建一个变量,并将上面函数的结果传递给它。

    Future<Pax> _futurePax;
    _futurePax = getPax();//can be used in initState
    

    使用builder方法

    FutureBuilder<Pax>(
            future: _futurePax,
            builder: (context, snapshot) {
    //use a listview/gridview or handle list indexes in any way you'd prefer
    //in the list you can get snapshot.data.instructions[index].id 
       })
    

    【讨论】:

    • 我用这个更新了,但它似乎没有用,有什么线索吗?我添加了新代码。
    • @Claudio 的回答是否解决了您的问题
    • 是的。 app.quicktype.io 中有一个粘贴错误,它生成了不存在的父类,所以当我删除这些类时它起作用了。
    猜你喜欢
    • 2020-07-14
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多