skip to Main Content
  var result = await httpCalls(....);

  List<UserModel> users = [];

  await result['users'].map((e) async {
    Map<String, dynamic> a = jsonDecode(jsonEncode(e));
    users.add(UserModel.fromJson(a));
  }).toList();

I am receiving an array of UserModel from the http calls. Currently, I am converting one by one to add it to the List<UserModel> users.

Is there better way to do this?

2

Answers


  1. You can try this

    List<dynamic> parsedJson = jsonDecode("response here");
      List<UserModel> users = List<UserModel>.from(parsedJson.map<UserModel>((dynamic i) => UserModel.fromJson(i)));
    

    This will generate a list from the result of all UserModels

    Login or Signup to reply.
  2. It’s not clear why you’ve added the async keyword in your lambda, nor why you encode and then decode each element.

    The important trick with List.map<T>() is to give it a generic type. This way it returns an iterable of the correct type and, in turn, the toList will give you the correct type.

      final list = (results['users'] as List<dynamic>)
          .map<UserModel>((elem) => UserModel.fromJson(elem))
          .toList();
    

    This takes the List<dynamic> you get from the decoded JSON (you can probably omit the as that I added for emphasis) and calls map. By typing the map, the compiler knows that the lambda must return a UserModel – so it will end up with an iterable of only user models, which can then be turned into a list of them. Thus the compiler knows that list is a List<UserModel>.

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