我有一个 API,它返回的响应类似于本文中显示的响应。
我的响应返回列表中的对象,该对象仅包含一个 $ref 变量,该变量指向列表中某处具有相关 $id 的子对象。
我尝试了以下方法,但它不适用于更大更复杂的响应,我怀疑它会大大增加计算时间:
Future<List<Category>> getCategories() async {
String token = await FlutterSession().get("accessToken");
final response =
await http.get('$url/api/categories/', headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token,
});
if (response.statusCode == 200) {
categories = categoriesFromJson(response.body);
var incompleteCats = categories.where((c) => c.id == null);
incompleteCats.forEach((ic) {
categories.remove(ic);
var completeCat =
categories.where((s) => s.parent?.$id == ic.$ref).first.parent;
categories.add(completeCat);
});
return categories;
} else {
throw Exception('Failed to get categories');
}
}
API 响应示例
[
{
"$id": "3",
"Parent": {
"$id": "4",
"Parent": {
"$ref": "1"
},
"CategoryName": "General",
"Description": "Test",
"ParentCategoryId": 45,
"SortOrder": 2,
"Id": 49,
"IsDeleted": false,
"CreatedDate": "2009-11-29T00:00:00",
"CreatedByUserId": 1,
"UpdatedDate": "1900-01-01T00:00:00",
"UpdatedByUserId": null,
"State": 0
},
"CategoryName": "Country",
"Description": "Test",
"ParentCategoryId": 49,
"SortOrder": 3,
"Id": 47,
"IsDeleted": false,
"CreatedDate": "2019-11-29T00:00:00",
"CreatedByUserId": 1,
"UpdatedDate": "1900-01-01T00:00:00",
"UpdatedByUserId": null,
"State": 0
},
{
"$id": "16",
"Parent": {
"$ref": "4"
},
"CategoryName": "Other",
"Description": "Other",
"ParentCategoryId": 49,
"SortOrder": 7,
"Id": 61,
"IsDeleted": false,
"CreatedDate": "2020-06-05T09:13:50.863",
"CreatedByUserId": 1,
"UpdatedDate": "2020-06-05T09:13:50.863",
"UpdatedByUserId": 1,
"State": 0
},
{
"$ref": "4"
},
]