Reputation: 163
I am trying to fetch json data from this url- "https://jsonplaceholder.typicode.com/photos". And I am following this flutter cookbook tutorial - "https://flutter.dev/docs/cookbook/networking/background-parsing"
My model class looks like this-
class ModelData {
ModelData({
this.albumId,
this.id,
this.title,
this.url,
this.thumbnailUrl,
});
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
factory ModelData.fromJson(Map<String, dynamic> json) => ModelData(
albumId: json["albumId"] as int,
id: json["id"] as int,
title: json["title"] as String,
url: json["url"] as String,
thumbnailUrl: json["thumbnailUrl"] as String,
);
}
And my parseData method looks like this-
List<ModelData> parseData(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<ModelData>((json) => ModelData().fromJson(json)).toList();
}
The problem is in the last line of this method. It says "error: The method 'fromJson' isn't defined for the type 'ModelData'. (undefined_method at [flutter_rest] lib\main.dart:61)". i don't see any typo problem here. What might going wrong here?
Upvotes: 0
Views: 42
Reputation: 4569
Factory methods act like a static method but you are initialising the class by using ModelData()
.
Try like this:
ModelData.fromJson(json)
Upvotes: 3