0

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?

1
  • ModelData().fromJson(json) change it to ModelData.fromJson(json). Factory methods work like static functions Commented May 22, 2021 at 7:28

1 Answer 1

3

Factory methods act like a static method but you are initialising the class by using ModelData().
Try like this:

ModelData.fromJson(json)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.