【发布时间】: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<id>); 但它不起作用。显然已经构建了一些东西,但我不知道如何在调试级别(在 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吗?
-
我不确定什么是 quicktype,所以我可能会遗漏一些东西,但您共享的 json 没有
instructions属性。 -
app.quicktype.io 只需粘贴 json 并生成 dart 代码来映射它。 @ClaudioRedi
-
似乎 quicktype 正在生成一个不存在的父级别。
标签: json parsing flutter quicktype