给定一个不可修改的 JSON,您可以像这样从服务器获得:
{ "name": "someName",
"fields": [
{ "name": "field1",
"type": "text",
"subtype": "autofill",
"value": "someVal" },
{ "name": "field2",
"type": "text",
"subtype": "password",
"value": "somePass" },
{ "name": "field3",
"type": "number",
"subtype": "integer",
"value": 12 },
{ "name": "field4",
"type": "number",
"subtype": "double",
"value": 3.14 }
],
"etc": "etc"
}
冻结的模型应该是这样的:
@freezed
class ExampleSuperclass with _$ExampleSuperclass {
factory ExampleSuperclass({
String? name,
List<Field>? fields,
String? etc,
}) = _ExampleSuperclass;
factory ExampleSuperclass.fromJson(Map<String, dynamic> json) =>
_$ExampleSuperclassFromJson(json);
}
@Freezed(unionKey: 'type')
class Field with _$Field {
factory Field({
String? name,
String? type,
String? subtype,
}) = _Field;
factory Field.text({
String? name,
String? type,
String? subtype,
}) = _FieldText;
factory Field.number({
String? name,
String? type,
String? subtype,
}) = _FieldNumber;
factory Field.fromJson(Map<String, dynamic> json) => _$FieldFromJson(json);
}
但是您意识到您需要类型和子类型才能创建更多的 Field.number 和 Field.text 子类型,您如何实现自定义 fromJson 来完成这项工作?