我不確定到底發(fā)生了什么,因?yàn)槲业拇a運(yùn)行良好,但突然停止工作,我不認(rèn)為我改變了任何與此相關(guān)的東西。我在這件事上糾纏了兩天,搞不清楚自己做錯(cuò)了什么。API返回的數(shù)據(jù)是正確的,返回的狀態(tài)碼是200
我相信這個(gè)錯(cuò)誤與PTWorkoutPlanItem.fromJson()
函數(shù)有關(guān)。我不認(rèn)為這與List<AssignedUsers>
或List<WorkoutPlanItem>
模型有任何關(guān)系,因?yàn)楫?dāng)我將這些更改為dynamic
時(shí),錯(cuò)誤仍然會(huì)發(fā)生
錯(cuò)誤顯示
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
獲取數(shù)據(jù)的代碼:
getPlanData() async {
var data = PTWorkoutPlanItem.fromJson(
await get(url: 'pt/workouts/plan/' + planId.toString()));
}
// Console logged the response here and it is correct, so this function works
Future<dynamic> get({url}) async {
final response = await http.get(baseUrl + url, headers: headers);
print(response.statusCode);
dynamic res = json.decode(response.body);
return res;
}
models
class PTWorkoutPlanItem {
int id;
String title;
List<AssignedUsers> assignedUsers;
List<WorkoutPlanItem> workouts;
int ptId;
PTWorkoutPlanItem(
{this.id, this.title, this.assignedUsers, this.workouts, this.ptId});
factory PTWorkoutPlanItem.fromJson(Map<String, dynamic> json) {
return PTWorkoutPlanItem(
id: json['id'],
title: json['title'],
assignedUsers: List.from(json['assignedUsers'])
.map((item) => AssignedUsers.fromJson(item))
.toList(),
workouts: List.from(json['workouts'])
.map((item) => WorkoutPlanItem.fromJson(item))
.toList(),
ptId: json['ptId'],
);
}
}
class AssignedUsers {
int id;
String title;
AssignedUsers({this.id, this.title});
factory AssignedUsers.fromJson(Map<String, dynamic> json) {
return AssignedUsers(id: json['id'], title: json['title']);
}
}
class WorkoutPlanItem {
int id;
String title;
int duration;
int sets;
int rest;
WorkoutPlanItem({this.id, this.title, this.duration, this.sets, this.rest});
factory WorkoutPlanItem.fromJson(Map<String, dynamic> json) {
return WorkoutPlanItem(
id: json['id'],
title: json['title'],
duration: json['duration'],
sets: json['sets'],
rest: json['rest'],
);
}
}
這就是API中返回的內(nèi)容
{
"id": 1,
"title": "Pull day",
"assignedUsers": [
{
"id": 1,
"title": "josh"
},
{
"id": 2,
"title": "marus"
}
],
"workouts": [
{
"id": 4,
"title": "Workout item 4",
"duration": 10,
"sets": 3,
"rest": 3
},
{
"id": 1,
"title": "Workout item 1",
"duration": 10,
"sets": 3,
"rest": 3
}
],
"ptId": 1
}
試試這個(gè)。我添加了很多類型轉(zhuǎn)換,但最重要的部分是如何處理
List<dynamic>
并將每個(gè)元素轉(zhuǎn)換為Map<String, dynamic>
:此外,這里還有一個(gè)與Dart 2.12兼容的版本,其中
required
已添加到命名參數(shù)中,因?yàn)樗鼈兌疾辉试S是null
,并且沒(méi)有任何默認(rèn)值:更新:您是否也可以嘗試將您的方法更改為: