记录一个bug,再记录一下自己的新“发现”。
在flutter里面将后端获取的数据转换成本地模型的时候,在模型里面使用了其他模型类型(比如外键这种)
数据结构如下(JSON):
{
"Id": "74a23e17-c659-4557-9e06-f57005f4ffc0",
"Name": "6",
"Owner": {
"id": "0c5246ca-2978-468d-9f19-4412124df74b",
"username": "admin",
"email": "admin@qq.com",
"root_drive": "72305989-9f2d-4a4b-8afc-9436ebaaa56c"
},
"Items": [
"2fce55ec-1373-4c7c-a0e1-2ea02dfc9ca1",
"77f672f4-c464-4133-b24f-9aea4ddedc63",
"986eb604-3817-4d08-9458-1c8bf7fae34e"
],
"Root": {
"Id": "2fce55ec-1373-4c7c-a0e1-2ea02dfc9ca1",
"Name": "6",
"Owner": "0c5246ca-2978-468d-9f19-4412124df74b",
"Creator": "0c5246ca-2978-468d-9f19-4412124df74b",
"IsShared": true,
"ParentFolder": null,
"SubFolders": [],
"Files": [
"77f672f4-c464-4133-b24f-9aea4ddedc63",
"986eb604-3817-4d08-9458-1c8bf7fae34e"
],
"DateCreated": "2023-01-30T16:30:50.176712+08:00",
"DateModified": "2023-02-05T09:23:44.299846+08:00"
},
"CreatedTime": "2023-02-06T12:09:50.989876+08:00",
"OutdatedTime": null,
"Members": [
{
"id": "0c5246ca-2978-468d-9f19-4412124df74b",
"username": "admin",
"email": "admin@qq.com",
"root_drive": "72305989-9f2d-4a4b-8afc-9436ebaaa56c"
},
{
"id": "2de2912a-de5a-4945-bf7f-690accf81b02",
"username": "tianc",
"email": "141@qq.com",
"root_drive": "07286978-69a2-4555-9139-ec66fa74e3d5"
}
],
"Code": "BvpW",
"ShareType": 1,
"Description": "无"
}
可以看到里面比如“Owner”字段是嵌套的,在前端想要获取详细数据就要有对应的模型。
flutter中初始模型如下:
class ShareItem {
String id;
String name;
User owner;
List<dynamic> items;
Folder root;
String createdTime;
dynamic outdatedTime;
List<dynamic> members;
String code;
int sharetype;
String description;
ShareItem(
this.id,
this.name,
this.owner,
this.items,
this.root,
this.createdTime,
this.outdatedTime,
this.members,
this.code,
this.sharetype,
this.description);
factory ShareItem.fromjson(Map<String, dynamic> json) {
return ShareItem(
json['Id'],
json['Name'],
json['Owner'],
json['Items'],
json['Root'],
json['CreatedTime'],
json['OutdatedTime'],
json['Members'],
json['Code'],
json['ShareType'],
json['Description']);
}
}
修改后如下:
class ShareItem {
String id;
String name;
User owner;
List<dynamic> items;
Folder root;
String createdTime;
dynamic outdatedTime;
List<dynamic> members;
String code;
int sharetype;
String description;
ShareItem(
this.id,
this.name,
this.owner,
this.items,
this.root,
this.createdTime,
this.outdatedTime,
this.members,
this.code,
this.sharetype,
this.description);
factory ShareItem.fromjson(Map<String, dynamic> json) {
return ShareItem(
json['Id'],
json['Name'],
//修改User
User.fromjson(json['Owner']),
json['Items'],
//修改Folder
Folder.fromJson(json['Root']),
json['CreatedTime'],
json['OutdatedTime'],
json['Members'],
json['Code'],
json['ShareType'],
json['Description']);
}
}
如上修改之后就可以正常读取了