0

Here I'm trying to make a future listview builder, getting an error message: _TypeError (type 'List' is not a subtype of type 'Map') flutter. I need to get all data inside the post in the list view . Created model class using JSON to dart converter quicktype.io

Future Call

Future<Posts> getPosts() async {
  try {
    final response =
        await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));

    var data = jsonDecode(response.body);
    return Posts.fromJson(data);
  } catch (e) {
    print(e);
  }
}

Model

List<Posts> postsFromJson(String str) => List<Posts>.from(json.decode(str).map((x) => Posts.fromJson(x)));
String postsToJson(List<Posts> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Posts {
    Posts({
        this.userId,
        this.id,
        this.title,
        this.body,
    });

    int userId;
    int id;
    String title;
    String body;

    factory Posts.fromJson(Map<String, dynamic> json) => Posts(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
    );

    Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
    };
}


0

3 Answers 3

1

I think your API return list of Posts not just a single Post. first I suggest to rename your class name from Posts to Post then code below can solve your problem:

Future<List<Posts>> getPosts() async {
  try {
    final response =
        await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));

    var data = jsonDecode(response.body);
    return data.map<Posts>((data) => Posts.fromJson(json.decode(data))).toList();
  } catch (e) {
    print(e);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you should use:

return postsFromJson(data);

And make that function return a list, because in your response body it returns a List of objects, therefore using just Posts.fromJson() will give you this error, because Posts.fromJson() expects a single Map, and you gave it a List. If you want just one item you can access that item in the list and give it to Posts.fromJson() function

Comments

0

Change this:

var data = jsonDecode(response.body);

into this:

var data = (jsonDecode(response.body) as List<dynamic>).cast<Map<String, dynamic>>();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.