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
You can try this
This will generate a list from the result of all UserModels
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, thetoList
will give you the correct type.This takes the
List<dynamic>
you get from the decoded JSON (you can probably omit theas
that I added for emphasis) and callsmap
. By typing the map, the compiler knows that the lambda must return aUserModel
– 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 thatlist
is aList<UserModel>
.