skip to Main Content

I am successfully receiving a JSON object in the following function:

class PostsAPI extends WebService {
  final userStorage = UserStorage();

  Future<dynamic> getFeedPosts() async {
    final token = await userStorage.getUserToken();

    final response = await get(
      endpoint: '/api/posts',
      token: token,
    );

    if (response.statusCode != 200) {
      if (response.statusCode == 500) {
        throw PostsServerFailure();
      }
      throw PostsRequestFailure();
    }

    return response.body;
  }
}

My issue is, I simply cannot seem to convert the JSON into a List of type Post:

Future<List<Post>> getFeedPosts() async {
  final postsAPI = await _postsAPI.getFeedPosts();

  final posts = List<Post>.from(postsAPI['posts'].map(Post.fromJson())); // **HERE**

  return posts;
}

No matter what I attempt, I always end up with an error in the conversion.

Also, here is my Post fromMap and fromJson:

factory Post.fromMap(Map<String, dynamic> map) {
  return Post(
    author: Author.fromMap(map['author'] as Map<String, dynamic>),
    contentURL: (map['url'] ?? '') as String,
    uploadTime: DateTime.parse((map['created_at'] ?? '') as String),
    //videoTimeLength: map['length'] ?? '',
    gameName: (map['game'] ?? '') as String,
    description: (map['description'] ?? '') as String,
    viewCount: map['views'] as int,
    likeCount: map['likes'] as int,
    //comments: Comment.fromMap(map['comments']),
  );
}

factory Post.fromJson(dynamic source) =>
    Post.fromMap(json.decode(source as String) as Map<String, dynamic>);

Also, here is an example of the JSON i’m trying to receive:

{
  "success": true,
  "posts": [
     {
        "id": 38,
        "likes": 60,
        "views": 0,
        "createdAt": "2023-02-15T21:19:47.963Z",
        "content": {
            "id": 28,
            "url": "https://res.cloudinary.com/example.jpg"
        },
        "comments": {
            "count": 0
        },
        "game": {
            "id": 3,
            "name": "Minecraft"
        },
        "user": {
            "id": 5,
            "username": "teste1",
            "avatar_border": {
                "id": 1,
                "name": "delicate_savage",
                "createdAt": "2023-03-06T22:46:19.998Z",
                "updatedAt": "2023-03-06T22:46:21.842Z",
                "publishedAt": "2023-03-06T22:46:21.840Z"
            },
            "background": {
                "id": 1,
                "name": "background_5",
                "createdAt": "2023-03-06T22:45:57.978Z",
                "updatedAt": "2023-03-06T22:46:02.602Z",
                "publishedAt": "2023-03-06T22:46:02.599Z"
            },
            "profile_pic": null
        }
      },
      {
        "id": 37,
        "likes": 5003,
        "views": 0,
        "createdAt": "2023-02-15T21:18:38.451Z",
        "content": {
            "id": 29,
            "url": "https://res.cloudinary.com/example.jpg"
        },
        "comments": {
            "count": 0
        },
        "game": {
            "id": 4,
            "name": "Black ops 2"
        },
        "user": {
            "id": 8,
            "username": "mini",
            "avatar_border": {
                "id": 3,
                "name": "quit_while_youre_ahead",
                "createdAt": "2023-03-06T22:46:34.792Z",
                "updatedAt": "2023-03-06T22:46:35.630Z",
                "publishedAt": "2023-03-06T22:46:35.628Z"
            },
            "background": {
                "id": 1,
                "name": "background_5",
                "createdAt": "2023-03-06T22:45:57.978Z",
                "updatedAt": "2023-03-06T22:46:02.602Z",
                "publishedAt": "2023-03-06T22:46:02.599Z"
            },
            "profile_pic": null
        }
      },
    }
  ]
}

Any help would be very much appreciated!

2

Answers


  1. This line

    final posts = List<Post>.from(postsAPI['posts'].map(Post.fromJson()));
    

    Could be

    final json = jsonDecode(postAPI);
    
    final posts = List.from(json['posts']).map((e) => Post.fromMap(e)).toList();
    
    Login or Signup to reply.
  2. Use following website to convert your JSON to Model.
    Then

    YourCustomModel resp = YourCustomModel.fromJson(jsonDecode(response.bodyString ?? ''));
    

    This resp have all the data you need. I am confident that you’ll figure out remaining.

    PS. do not forget to change language to dart on website.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search