How to handle unused parameter from api in flutter? - json

My requirement for Dropdown only name and id, if I didn't include all parameters to file id didn't parse the object. it throws gson error.
How to create an object to handle this response for the unwanted parameters from API response in Flutter.
import 'package:meta/meta.dart';
import 'dart:convert';
class Customer {
Customer({
#required this.data,
#required this.status,
});
List<Datum> data;
int status;
factory Customer.fromRawJson(String str) => Customer.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Customer.fromJson(Map<String, dynamic> json) => Customer(
data: json["data"] == null ? null : List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
status: json["status"] == null ? null : json["status"],
);
Map<String, dynamic> toJson() => {
"data": data == null ? null : List<dynamic>.from(data.map((x) => x.toJson())),
"status": status == null ? null : status,
};
}
class Datum {
Datum({
#required this.id,
#required this.name,
#required this.contactPersonName,
#required this.mobileNo,
#required this.whatsAppNo,
#required this.user,
#required this.address,
#required this.gstNo,
#required this.creaditPeriod,
#required this.note,
#required this.created,
#required this.modified,
#required this.contactPersonEmail,
});
String id;
String name;
dynamic contactPersonName;
dynamic mobileNo;
dynamic whatsAppNo;
dynamic user;
dynamic address;
dynamic gstNo;
dynamic creaditPeriod;
dynamic note;
dynamic created;
dynamic modified;
dynamic contactPersonEmail;
factory Datum.fromRawJson(String str) => Datum.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
contactPersonName: json["contactPersonName"],
mobileNo: json["mobileNo"],
whatsAppNo: json["whatsAppNo"],
user: json["user"],
address: json["address"],
gstNo: json["gstNo"],
creaditPeriod: json["creaditPeriod"],
note: json["note"],
created: json["created"],
modified: json["modified"],
contactPersonEmail: json["contactPersonEmail"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null: name,
"contactPersonName": contactPersonName,
"mobileNo": mobileNo,
"whatsAppNo": whatsAppNo,
"user": user,
"address": address,
"gstNo": gstNo,
"creaditPeriod": creaditPeriod,
"note": note,
"created": created,
"modified": modified,
"contactPersonEmail": contactPersonEmail,
};
}
Any idea how to create small object with id and name parameters only.

Just include the parameters you need from the json to the Model.
For example:
class Datum {
final String name;
final String id;
Datum({this.name,this.id});
}

Related

String is not a subtype of Map<String, dynamic> in flutter

im using this json response to convert it to an object
json response
{"Data":"{\"IdToken\":\"eyJraWQiOiJxazZwYk9GZVdPWnRTbWorczlqMng2cDN5bUFUcXdDTlhMQ09Ic1JIOFNFPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyMmEwZjViMi03NTY3LTQwODQtYjUzYS0zMzhjNTE5NmNiYWQiLCJjb2duaXRvOmdyb3VwcyI6WyJCdXNpbmVzc19EZXZlbG9wbWVudF9SZWFkT25seSIsIk9wZXJhdGlvbl9MZXZlbF8xX1JlYWRPbmx5IiwiQnVzaW5lc3NfRGV2ZWxvcG1lbnRfTGV2ZWxfMyIsIkZhY2lsaXR5X1N0YWZmX01lbWJlciIsIk9wZXJhdGlvbl9MZXZlbF8zIiwiTWVtYmVyIiwiRmluYW5jZV9MZXZlbF8zIiwiRmluYW5jZV9MZXZlbF8yIiwiT3BlcmF0aW9uX0xldmVsXzEiLCJCdXNpbmVzc19EZXZlbG9wbWVudF9MZXZlbF8xIiwiQnVzaW5lc3NfRGV2ZWxvcG1lbnRfTGV2ZWxfMiIsIlByaXZpbGVnZWRfUmVwb3J0c19BY2Nlc3MiLCJFbXBsb3llcl9GYWNpbGl0YXRvciIsIkZpbmFuY2VfTGV2ZWxfMSIsIk9wZXJhdGlvbl9MZXZlbF8yIiwiQWRtaW4iXSwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC5hcC1zb3V0aGVhc3QtMi5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMl81ODhOY1o0YmciLCJwaG9uZV9udW1iZXJfdmVyaWZpZWQiOmZhbHNlLCJjb2duaXRvOnVzZXJuYW1lIjoia2V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383QxaLasJqnpwDPpoVbjVpEEgM676RUDwowrpPXNKY9FOg1wgQAJTOR6Nm6bGE5tvVQhKnppOSDtX6uYLCLwhK66B2FIq0SgHJn-3CmiL0p6_SRGhHYhcZ09VdvieUDb5DhGWTxDJICjpdmU7ma6IdoqLfbfD_vzeKpVWIfx8yELiRjZw_cedZ89KBL0AlX_gg15ccs7dWp3_k8j9ZAJuOjp-aEarsrhSqGBBMFqg6GFAvSQvCQq3UjC7AFWpvBftuZY6SjF5XeFQFdRfyTZ-3G1ToKUYS7gniMxhT9lmgDp7uU5oPLlPE8O5d2PcgrbekajO1nOq4-obQZhFYTNQbV6V76ktq8ydW6icX-iyJM2nvRSPxvDcm0L5Z8c4Pl7_uJAZfck-28rL0-FRW-TwD16nkM4SYn961GUpqwbvIA6AdBU2aGrJGIioeXcnAAMVshejWhhn710Qq4A0--HJdmsywGnRSonUfO56cqP0kQNDgoh35HIDedjguzZAOYyFdflYo4jR8QjbgYYZSv7oLliZKI-6DwfEhJRuYIdVMIt7zTdNpaEnUOIPuhziF67zkAgXvwaQhDK4oP_b4jRXdJ1j2lKeSeJbE5CuQ8TrMbb8YEHHZ0FCTX61PJVEtEOgBhgINClgF2-2gmzcEVylftv3ap56BNV76r7cEnUeIEQnhi1x6emtCzUyci-5j6KIyXZGstuM-5zPod5y47RXKxyP8w7PxQX0mBrNSpU_Lkw0H37RuQTbWnuTMagtGeYj3z33poSVpYTOCUs7RAyg3eVMNMDJWuH598Sew5Vf7nK.cYy20EQngV7xyTsUBWHy0g\"}","Name":null,"Message":null,"WaitInSeconds":0,"Success":true,"Errors":[],"ErrorNumber":0}
model class
import 'dart:convert';
JwtTokenResponseModel jwtTokenResponseModelFromJson(String str) =>
JwtTokenResponseModel.fromJson(json.decode(str));
String jwtTokenResponseModelToJson(JwtTokenResponseModel data) =>
json.encode(data.toJson());
class JwtTokenResponseModel {
JwtTokenResponseModel({
this.data,
this.name,
this.message,
this.waitInSeconds,
this.success,
this.errors,
this.errorNumber,
});
Data? data;
String? name;
String? message;
int? waitInSeconds;
bool? success;
List<dynamic>? errors;
int? errorNumber;
factory JwtTokenResponseModel.fromJson(Map<String, dynamic> json) =>
JwtTokenResponseModel(
data: Data.fromJson(json["Data"]),
name: json["Name"],
message: json["Message"],
waitInSeconds: json["WaitInSeconds"],
success: json["Success"],
errors: List<dynamic>.from(json["Errors"].map((x) => x)),
errorNumber: json["ErrorNumber"],
);
Map<String, dynamic> toJson() => {
"Data": data!.toJson(),
"Name": name,
"Message": message,
"WaitInSeconds": waitInSeconds,
"Success": success,
"Errors": List<dynamic>.from(errors!.map((x) => x)),
"ErrorNumber": errorNumber,
};
#override
String toString() {
return toJson().toString();
}
}
class Data {
Data({
this.idToken,
this.accessToken,
this.refreshToken,
});
String? idToken;
String? accessToken;
String? refreshToken;
factory Data.fromJson(Map<String, dynamic> json) => Data(
idToken: json["IdToken"],
accessToken: json["AccessToken"],
refreshToken: json["RefreshToken"],
);
Map<String, dynamic> toJson() => {
"IdToken": idToken,
"AccessToken": accessToken,
"RefreshToken": refreshToken,
};
#override
String toString() {
return toJson().toString();
}
}
When calling the converter here
final converted = json.decode(res);
return JwtTokenResponseModel.fromJson(converted);
I get the error String is not a subtype of Map<String, dynamic>.
how can I rectify this error.
any help is welcome heartedly.
this line causes the error I might say " data: Data.fromJson(json["Data"]),"
replace it by Data.fromJson( json.decode(json["Data"]))
to check if it's really the line causes the issue print it a see if it's a string or map

How to whole json response store in dart model and access that response via dart model instance in flutter

I'm trying to store my whole JSON response in the dart model class. but the response is not stored in the model.
I got this error in my debug console
this is my JSON response
{
"status": "success",
"message": "retrived successfully",
"data": [
{
"id": 1,
"name": "NEET RAJKOT",
"logo": "https://via.placeholder.com/150/92c952"
},
{
"id": 2,
"name": "MEDICAL",
"logo": "https://via.placeholder.com/150/771796"
},
{
"id": 3,
"name": "NEET",
"logo": "https://via.placeholder.com/150/24f355"
}
]
}
This code is how to I get response and store in model class
response = await http.get(
Uri.parse('api_url'),
headers: {""});
String data = json.decode(response.body);
CoursesModel coursesModel = CoursesModel.fromJson(data);
List<Data> coursesData = coursesModel.data;
This my model class
import 'dart:convert';
import 'package:flutter/foundation.dart';
class CoursesModel {
String status;
String message;
List<Data> data;
CoursesModel({
required this.status,
required this.message,
required this.data,
});
CoursesModel copyWith({
String? status,
String? message,
List<Data>? data,
}) {
return CoursesModel(
status: status ?? this.status,
message: message ?? this.message,
data: data ?? this.data,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'status': status,
'message': message,
'data': data.map((x) => x.toMap()).toList(),
};
}
factory CoursesModel.fromMap(Map<String, dynamic> map) {
return CoursesModel(
status: map['status'] as String,
message: map['message'] as String,
data: List<Data>.from((map['data'] as List<int>).map<Data>((x) => Data.fromMap(x as Map<String,dynamic>),),),
);
}
String toJson() => json.encode(toMap());
factory CoursesModel.fromJson(String source) => CoursesModel.fromMap(json.decode(source) as Map<String, dynamic>);
#override
String toString() => 'CoursesModel(status: $status, message: $message, data: $data)';
#override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is CoursesModel &&
other.status == status &&
other.message == message &&
listEquals(other.data, data);
}
#override
int get hashCode => status.hashCode ^ message.hashCode ^ data.hashCode;
}
class Data {
int id;
String name;
String logo;
Data({
required this.id,
required this.name,
required this.logo,
});
Data copyWith({
int? id,
String? name,
String? logo,
}) {
return Data(
id: id ?? this.id,
name: name ?? this.name,
logo: logo ?? this.logo,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'name': name,
'logo': logo,
};
}
factory Data.fromMap(Map<String, dynamic> map) {
return Data(
id: map['id'] as int,
name: map['name'] as String,
logo: map['logo'] as String,
);
}
String toJson() => json.encode(toMap());
factory Data.fromJson(String source) => Data.fromMap(json.decode(source) as Map<String, dynamic>);
#override
String toString() => 'Data(id: $id, name: $name, logo: $logo)';
#override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Data &&
other.id == id &&
other.name == name &&
other.logo == logo;
}
#override
int get hashCode => id.hashCode ^ name.hashCode ^ logo.hashCode;
}
use json_serializable (https://pub.dev/packages/json_serializable) package.
annotate class with #JsonSerilzable (and field with #JsonKey if needed). see the documentation for details.
I'm giving a lot of effort then I got a solution
1st I change fromJson to fromMap and my response takes as a Map
data = json.decode(coursesResponse.body);
coursesModel = CoursesModel.fromMap(data as Map<String,dynamic>);
coursesData = coursesModel.data!;
2nd Change is in the Model class
old-line code in fromMap Method List has List int
factory CoursesModel.fromMap(Map<String, dynamic> map) {
return CoursesModel(
status: map['status'] != null ? map['status'] as String : null,
message: map['message'] != null ? map['message'] as String : null,
data: map['data'] != null ? List<Data>.from((map['data'] as List<int>).map<Data?>((x) => Data.fromMap(x as Map<String,dynamic>),),) : null,
);
}
to change List dynamic
factory CoursesModel.fromMap(Map<String, dynamic> map) {
return CoursesModel(
status: map['status'] != null ? map['status'] as String : null,
message: map['message'] != null ? map['message'] as String : null,
data: map['data'] != null ? List<Data>.from((map['data'] as List<dynamic>).map<Data?>((x) => Data.fromMap(x as Map<String,dynamic>),),) : null,
);
}

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' JSON Mapinng into model

hello everyone I'm trying to fetch JSON from API, but I'm getting this error while mapping the JSON into the model I created it type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
this is the JSON response
{"data":{"userinfo":[{"firstname":"MAEN","lastname":"NASSAN","email":"maen.alnassan#outlook.com","active_status":0,"dark_mode":0,"messenger_color":"#2180f3","avatar":"avatar.png","gender":"male","region":"Turkey","birthyear":"2021","birthday":"1","birthmonth":"January","phonenumber":53105311,"category":"0","profilestatus":"private","ban":"0","banReason":"0","banDurationByDays":"0","email_verified_at":null,"created_at":"2021-05-24T16:27:52.000000Z","updated_at":"2021-05-24T16:27:52.000000Z"}],"userfriendsPosts":[{"postid":1,"userid":3,"posttitle":"Post 1 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:49:48.000000Z","updated_at":"2021-05-22T20:49:48.000000Z"},{"postid":3,"userid":3,"posttitle":"Post 2 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:58:40.000000Z","updated_at":"2021-05-22T20:58:40.000000Z"},{"postid":4,"userid":3,"posttitle":"Post 3 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:58:43.000000Z","updated_at":"2021-05-22T20:58:43.000000Z"}],"usernotifications":[],"userlikes":[]}}
and this is the Model Class
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
Data({
this.data,
});
DataClass data;
factory Data.fromJson(Map<String, dynamic> json) => Data(
data: DataClass.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class DataClass {
DataClass({
this.userinfo,
this.userfriendsPosts,
this.usernotifications,
this.userlikes,
});
List<Userinfo> userinfo;
List<UserfriendsPost> userfriendsPosts;
List<dynamic> usernotifications;
List<dynamic> userlikes;
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
userinfo: List<Userinfo>.from(json["userinfo"].map((x) => Userinfo.fromJson(x))),
userfriendsPosts: List<UserfriendsPost>.from(json["userfriendsPosts"].map((x) => UserfriendsPost.fromJson(x))),
usernotifications: List<dynamic>.from(json["usernotifications"].map((x) => x)),
userlikes: List<dynamic>.from(json["userlikes"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"userinfo": List<dynamic>.from(userinfo.map((x) => x.toJson())),
"userfriendsPosts": List<dynamic>.from(userfriendsPosts.map((x) => x.toJson())),
"usernotifications": List<dynamic>.from(usernotifications.map((x) => x)),
"userlikes": List<dynamic>.from(userlikes.map((x) => x)),
};
}
class UserfriendsPost {
UserfriendsPost({
this.postid,
this.userid,
this.posttitle,
this.post,
this.likesCounter,
this.commentsCounter,
this.category,
this.createdAt,
this.updatedAt,
});
int postid;
int userid;
String posttitle;
String post;
int likesCounter;
int commentsCounter;
String category;
DateTime createdAt;
DateTime updatedAt;
factory UserfriendsPost.fromJson(Map<String, dynamic> json) => UserfriendsPost(
postid: json["postid"],
userid: json["userid"],
posttitle: json["posttitle"],
post: json["post"],
likesCounter: json["likesCounter"],
commentsCounter: json["commentsCounter"],
category: json["category"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"postid": postid,
"userid": userid,
"posttitle": posttitle,
"post": post,
"likesCounter": likesCounter,
"commentsCounter": commentsCounter,
"category": category,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Userinfo {
Userinfo({
this.firstname,
this.lastname,
this.email,
this.activeStatus,
this.darkMode,
this.messengerColor,
this.avatar,
this.gender,
this.region,
this.birthyear,
this.birthday,
this.birthmonth,
this.phonenumber,
this.category,
this.profilestatus,
this.ban,
this.banReason,
this.banDurationByDays,
this.emailVerifiedAt,
this.createdAt,
this.updatedAt,
});
String firstname;
String lastname;
String email;
int activeStatus;
int darkMode;
String messengerColor;
String avatar;
String gender;
String region;
String birthyear;
String birthday;
String birthmonth;
int phonenumber;
String category;
String profilestatus;
String ban;
String banReason;
String banDurationByDays;
dynamic emailVerifiedAt;
DateTime createdAt;
DateTime updatedAt;
factory Userinfo.fromJson(Map<String, dynamic> json) => Userinfo(
firstname: json["firstname"],
lastname: json["lastname"],
email: json["email"],
activeStatus: json["active_status"],
darkMode: json["dark_mode"],
messengerColor: json["messenger_color"],
avatar: json["avatar"],
gender: json["gender"],
region: json["region"],
birthyear: json["birthyear"],
birthday: json["birthday"],
birthmonth: json["birthmonth"],
phonenumber: json["phonenumber"],
category: json["category"],
profilestatus: json["profilestatus"],
ban: json["ban"],
banReason: json["banReason"],
banDurationByDays: json["banDurationByDays"],
emailVerifiedAt: json["email_verified_at"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"firstname": firstname,
"lastname": lastname,
"email": email,
"active_status": activeStatus,
"dark_mode": darkMode,
"messenger_color": messengerColor,
"avatar": avatar,
"gender": gender,
"region": region,
"birthyear": birthyear,
"birthday": birthday,
"birthmonth": birthmonth,
"phonenumber": phonenumber,
"category": category,
"profilestatus": profilestatus,
"ban": ban,
"banReason": banReason,
"banDurationByDays": banDurationByDays,
"email_verified_at": emailVerifiedAt,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
and this is the API request function
static Future<List<Data>> getData(token) async{
Dio dio = new Dio();
dio.options.headers["Authorization"] = "bearer $token";
dio.options.headers["Content-Type"] = 'application/json';
dio.options.headers["Accept"] = 'application/json';
await dio.get(url,).then((response) {
final List<Data> _data = dataFromJson(response.data) as List<Data>;
return _data;
}
).catchError((error) => print(error));
}
I tried all the method to fetch the data and the complex JSON List but it's always ending withe errors looks like this errors
The error you're getting is telling you: "your code expects a String, but you gave it a _InternalLinkedHashMap<String, dynamic> (i.e. a Map<String, dynamic>)".
It's not clear where the error is happening, but my guess is that response.data is a Map<String, dynamic>, but dataFromJson expects a String, and this line is causing the error.
If you look at the docs for Dio.get() (https://pub.dev/documentation/dio/latest/dio/Dio/get.html),
you can see the signature is:
Future<Response<T>> get<T>(String path, { ... });
When you call dio.get(url) without passing a type parameter, it defaults to dynamic, which essentially turns off type-checking. If you expect your api to return a String, you can provide that to dio by using: dio.get<String>(url).
However, if you're immediately going to jsonDecode it, you could modify dataFromJson to accept a Map<String, dynamic> rather than a String, and skip the jsonDecode step.
Finally, I'd recommend you to check out a json library (json_serializable is very easy to get started with). Hand writing json serialization code is repetitive and error-prone. Instead of manually writing your toJson() and fromJson() functions, you simply define stubs, and you can generate serialization code at compile time.
https://pub.dev/packages/json_serializable

Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'

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
}
Try this. I have added a lot of type casts but the most important part is how I handle the List<dynamic> and cast each element to Map<String, dynamic>:
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'] as int,
title: json['title'] as String,
assignedUsers: (json['assignedUsers'] as List<dynamic>)
.cast<Map<String, dynamic>>()
.map((item) => AssignedUsers.fromJson(item))
.toList(),
workouts: (json['workouts'] as List<dynamic>)
.cast<Map<String, dynamic>>()
.map((item) => WorkoutPlanItem.fromJson(item))
.toList(),
ptId: json['ptId'] as int,
);
}
}
class AssignedUsers {
int id;
String title;
AssignedUsers({this.id, this.title});
factory AssignedUsers.fromJson(Map<String, dynamic> json) {
return AssignedUsers(id: json['id'] as int, title: json['title'] as String);
}
}
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'] as int,
title: json['title'] as String,
duration: json['duration'] as int,
sets: json['sets'] as int,
rest: json['rest'] as int,
);
}
}
Also, here is a Dart 2.12 compatible version where required as been added to the named parameters since they are all not allowed to be null and does not have any default value:
class PTWorkoutPlanItem {
int id;
String title;
List<AssignedUsers> assignedUsers;
List<WorkoutPlanItem> workouts;
int ptId;
PTWorkoutPlanItem(
{required this.id,
required this.title,
required this.assignedUsers,
required this.workouts,
required this.ptId});
factory PTWorkoutPlanItem.fromJson(Map<String, dynamic> json) {
return PTWorkoutPlanItem(
id: json['id'] as int,
title: json['title'] as String,
assignedUsers: (json['assignedUsers'] as List<dynamic>)
.cast<Map<String, dynamic>>()
.map((item) => AssignedUsers.fromJson(item))
.toList(),
workouts: (json['workouts'] as List<dynamic>)
.cast<Map<String, dynamic>>()
.map((item) => WorkoutPlanItem.fromJson(item))
.toList(),
ptId: json['ptId'] as int,
);
}
}
class AssignedUsers {
int id;
String title;
AssignedUsers({required this.id, required this.title});
factory AssignedUsers.fromJson(Map<String, dynamic> json) {
return AssignedUsers(id: json['id'] as int, title: json['title'] as String);
}
}
class WorkoutPlanItem {
int id;
String title;
int duration;
int sets;
int rest;
WorkoutPlanItem(
{required this.id,
required this.title,
required this.duration,
required this.sets,
required this.rest});
factory WorkoutPlanItem.fromJson(Map<String, dynamic> json) {
return WorkoutPlanItem(
id: json['id'] as int,
title: json['title'] as String,
duration: json['duration'] as int,
sets: json['sets'] as int,
rest: json['rest'] as int,
);
}
}
Update: Can you also try change your method into this:
Future<Map<String, dynamic>> get({url}) async {
final response = await http.get(baseUrl + url, headers: headers);
print(response.statusCode);
final res = json.decode(response.body) as Map<String, dynamic>;
return res;
}

_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

I am learning Dart and Flutter. Now I am tasting JSON as a persistence method. I get lots of errors, all concerning Types and stuff. This is the latest error I have experienced: _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>').
This is the class:
import './topic.dart';
class Subject {
String name;
int order;
bool isMajor;
List<Topic> topics;
Subject({this.name, this.order, this.isMajor, this.topics});
factory Subject.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Subject(
name: json['name'],
order: json['order'],
isMajor: json['isMajor'],
topics: [Topic.fromJSON(json['topics'])]);
} else {
return null;
}
}
}
The topic class is this:
import './content.dart';
class Topic {
String name;
int order;
List<Content> contents;
Topic({this.name, this.order, this.contents});
factory Topic.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Topic(
name: json['name'],
order: json['order'],
contents: [Content.fromJSON(json['contents'])]);
} else {
return null;
}
}
}
The error raises here: [Topic.fromJSON(json['topics'])].
Can anyone help? Thank you!
The topics should be
topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),
Because you did not provide Content class, I assume it have name and order attribute
You can use Subject subject = subjectFromJson(jsonString); to parse jsonString
full related class
// To parse this JSON data, do
//
// final subject = subjectFromJson(jsonString);
import 'dart:convert';
Subject subjectFromJson(String str) => Subject.fromJson(json.decode(str));
String subjectToJson(Subject data) => json.encode(data.toJson());
class Subject {
String name;
int order;
bool isMajor;
List<Topic> topics;
Subject({
this.name,
this.order,
this.isMajor,
this.topics,
});
factory Subject.fromJson(Map<String, dynamic> json) => Subject(
name: json["name"],
order: json["order"],
isMajor: json["isMajor"],
topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"order": order,
"isMajor": isMajor,
"topics": List<dynamic>.from(topics.map((x) => x.toJson())),
};
}
class Topic {
String name;
int order;
List<Content> contents;
Topic({
this.name,
this.order,
this.contents,
});
factory Topic.fromJson(Map<String, dynamic> json) => Topic(
name: json["name"],
order: json["order"],
contents: List<Content>.from(json["contents"].map((x) => Content.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"order": order,
"contents": List<dynamic>.from(contents.map((x) => x.toJson())),
};
}
class Content {
String name;
int order;
Content({
this.name,
this.order,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
name: json["name"],
order: json["order"],
);
Map<String, dynamic> toJson() => {
"name": name,
"order": order,
};
}