Flutter error: list<dynamic> is not a subtype of type Map<dynamic, dynamic>
179
Solution 1
"images": [{"small": "link", "large": "link"}]
this is a map of list and you are casting it to map of string.
Either use "images": {"small": "link", "large": "link"}
or use
factory Images.fromJson(List<dynamic> json) {
return Images(
small : json[0]["small"] as String,
large : json[0]["large"] as String
);}
Solution 2
You can try using this model. :
import 'dart:convert';
Test testFromJson(String str) => Test.fromJson(json.decode(str));
String testToJson(Test data) => json.encode(data.toJson());
class Test {
Test({
this.id,
this.title,
this.images,
});
int id;
String title;
List<Images> images;
factory Test.fromJson(Map<String, dynamic> json) => Test(
id: json["id"],
title: json["title"],
images: List<Images>.from(json["images"].map((x) => Images.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"images": List<dynamic>.from(images.map((x) => x.toJson())),
};
}
class Images {
Images({
this.small,
this.large,
});
String small;
String large;
factory Images.fromJson(Map<String, dynamic> json) => Images(
small: json["small"],
large: json["large"],
);
Map<String, dynamic> toJson() => {
"small": small,
"large": large,
};
}
Here List of images has been directly mapped to respective Image Class Objects which solves your problem.
Author by
Ranjan Sigdel
Updated on December 20, 2022Comments
-
Ranjan Sigdel over 1 year
My JSON is somewhat like this:
{"data":{"id":1,"title":"Title 1", "images": [{"small": "link", "large": "link"}]}}
My model class:
class Test { final int id; final String title; final Images images; Test({required this.id, required this.title, required this.images}); Test.fromJson(Map<dynamic, dynamic> parsedJson) : id = parsedJson["id"], title = parsedJson["title"], images = Images.fromJson(parsedJson['images']); class Images { final String small; final String large; Images({ required this.small, required this.large }); factory Images.fromJson(Map<dynamic, dynamic> json) { return Images( small : json["small"] as String, large : json["large"] as String );} }
Here is my api call:
static Future<Test> getTest(int id) async{ final response = await http.get(Uri.parse("url_here")); if(response.statusCode == 200){ Map<String, dynamic> json = jsonDecode(response.body); dynamic body = json['data']; Test test = Test.fromJson(body); return test; } else{ throw("message"); } }
How do I get images.small in view class? Please let me know if I need to clear my question. I'm getting an error list is not a subtype of type Map<dynamic, dynamic> while trying to fetch images but I'm not able to covert map to list.