Suppose I have a json object like this:
{
"sort": "asc",
"page": {
"next": "asdfg",
"prev": "kljekj"
}
}
I wrote a datamodel in dart like this:
class AllPage{
String sort;
Page page;
AllPage({this.sort, this.page});
AllPage.fromJson(Map<String, dynamic> json) {
return AllPage(
sort = json['sort'],
page = Page.fromJson(json['page']));
}
}
class Page {
String next;
String prev;
Page({this.next, this.prev});
Page.fromJson(Map<String, dynamic> json) {
return Page(
next = json['next'],
prev = json['prev']);
}
}
I have seen countless examples in which this works. However, I am getting an error in my AppPage class, inside Page.FromJson(json['page']). The error says: "The argument type 'dynamic' can't be assigned to the parameter type 'Map>string, dynamic>'.
I am new to flutter/dart. So this could be something simple that I am missing. Any help is greatly appreciated. Thank you!
json['page'] returns a dynamic since it could be really anything. You need to do some casting
class AllPage {
String sort;
Page page;
AllPage({this.sort, this.page});
factory AllPage.fromJson(Map<String, dynamic> json) {
return AllPage(
sort: json['sort'].toString(),
page: Page.fromJson(json['page'] as Map),
);
}
}
class Page {
String next;
String prev;
Page({this.next, this.prev});
factory Page.fromJson(Map json) {
return Page(
next: json['next'].toString(),
prev: json['prev'].toString(),
);
}
}
Note that it is assuming a lot about the structure of the json. You should add checks in such as what if json['page'] or json['next'] is null.
Also fixed up some of the compile issues around the use of constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With