0

new to Flutter, I managed to parse this response from a RESt api:

Provider:

  factory Contacts.fromList(final List<Map<String, dynamic>> list) {
    final Contacts contacts = Contacts();
    for (final Map<String, dynamic> map in list) {
      contacts.add(Contact.fromMap(map));
    }
    return contacts;
  }

then in my service:

 if (response.statusCode == 200) {
      return Contacts.fromList(
          jsonDecode(response.body).cast<Map<String, dynamic>>());

when the data comes in this format:

[
    {
        "id": 1,
        "first_name": "Dave",
        "last_name": "Laweles",
        "email": "[email protected]",

This all works perfectly, but now, my dummy API is returning the data in this format:

{
    "data": [
       {
        "id": 1,
        "first_name": "Dave",
        "last_name": "Laweles",
        "email": "[email protected]",
        }, .....
     ],
    "total": 100,
    "page": 0,
    "limit": 10,
    "offset": 0
}

And now I cannot figure out how to change my Provider factory constructor to Parse correctly this result object. Besides the fact that now the response is wrapped in another object, I also need to retrieve the Pagination data (total, page, limit) as well in my Parsing.

1 Answer 1

1

You can do it like below:

actory Contacts.fromList(final List<Map<String, dynamic>> list) {
    final Contacts contacts = Contacts();
    for (final Map<String, dynamic> map in list['data']) {
      contacts.add(Contact.fromMap(map));
    }
    return contacts;
  }

And I hope it works for you.

Sign up to request clarification or add additional context in comments.

1 Comment

this was the first thing I tried and does not work The type 'Map<String, dynamic>' used in the 'for' loop must implement Iterable.dartfor_in_of_invalid_type The argument type 'String' can't be assigned to the parameter type 'int' I will also need to extrapolate the other data on the same level as "data"

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.