I'm not exactly sure whats happened because my code was working fine but all of a sudden stopped working and I dont think I changed anything in relation to this. I've been stuck on this for two days and can't figure out what I'm doing wrong. The data being returned from the API is correct and it returns with a status code of 200
I believe the error is something to do with the PTWorkoutPlanItem.fromJson() function. I dont think it has anything to do with the List<AssignedUsers> or List<WorkoutPlanItem> models in the PTWorkoutPlanItem model as when I change these to dynamic, the error still occurs
The error says
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
code to get the data:
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'],
);
}
}
this is what gets retuned in the API
{
"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
}