-1

SO I am using this API from a rest service that sends me data in the following json format.

API RESPONSE

"data": [
    {
        "id": 3,
        "title": "Lorem Ipsum Post",
        "excerpt": "This is the excerpt for the Lorem Ipsum Post",
        "body": "<p>This is the body of the lorem ipsum post</p>",
        "created_at": "2021-08-03T11:54:52.000000Z",
        "updated_at": "2021-08-03T11:54:52.000000Z"
    },
    {
        "id": 4,
        "title": "My Sample Post",
        "excerpt": "This is the excerpt for the sample Post",
        "body": "<p>This is the body for the sample post, which includes the body.</p>\n                <h2>We can use all kinds of format!</h2>\n                <p>And include a bunch of other stuff.</p>",
        "created_at": "2021-08-03T11:54:52.000000Z",
        "updated_at": "2021-08-03T11:54:52.000000Z"
    },
]

And I use the following method to insert the values coming from the api response into a list of that I need to use later on.

Method I use

Future<List<Post>> getAllPosts(String token) async {
final ApiResponse apiResponse = await _apiBaseHelper.get(
    "https://test.sugayo.com/api/cg/posts/limit/3",token);
Post allPost=Post.fromJson(jsonDecode(apiResponse.data));
List<Post> allPostList=[Post(id: allPost.id, subtitle: allPost.subtitle, secondaryText: allPost.secondaryText, body: allPost.body)];
return allPostList;

}

In the terminal I get this error Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'List' and the returned list is null.Pls help

Kavishka Rajapakshe
  • 537
  • 1
  • 8
  • 23
  • 1
    Try my answer for here for fetch data from API here https://stackoverflow.com/a/68533647/13997210 or here https://stackoverflow.com/a/68594656/13997210 hope it help to you – Ravindra S. Patil Aug 06 '21 at 04:19
  • Please add full API response. Is "data" block enclosed by curly brackets? And what does `Post.fromJson()` take as input. Please add that method also in the question. – Kshitij Dhakal Aug 06 '21 at 04:35

2 Answers2

1

Since response is a list of Posts not just a Post you should get List like this:

Map<String, dynamic> result = json.decode(response.body);
List<Post> posts = List<Post>.from(result['data'].map((dynamic row) => Post.fromJson(row)));
Zahra
  • 2,231
  • 3
  • 21
  • 41
1
Future<List<Post>> getAllPosts(String token) async {

final ApiResponse apiResponse = await _apiBaseHelper.get(
    "https://test.sugayo.com/api/cg/posts/limit/3",token);
    
final responsebody=jsonDecode(apiResponse.body) as List;

final allPostList= responsebody['data'].map((e) => Post.fromJson(e)).toList();

return allPostList;