Reputation: 1280
The list returned from this code is empty. assume that formatUser is an async method that formats the user from the remote to a suitable format. why is that filterUsers list does'nt change when we map the other list?
Future<List<User>> fetchUsers() async{
final list<User> usersFromRemote = await getUserFromRemote();
final List<User> filterUsers = [];
usersFromRemote.map((user) async {
if(user.name != 'jim')
{
filterUsers.add(await formatUser(user));
}
});
return filterUsers;
}
Upvotes: 0
Views: 48
Reputation: 404
Use forEach() instead of map()
. According to the docs, unless the iterable returned by map()
is iterated over, the transforming function will not be called.
Upvotes: 0
Reputation: 2341
You are using map
wrongly. You need to use filter(aka where
) and map
for your use case.
Future<List<User>> fetchUsers() async {
final List<User> usersFromRemote = await getUserFromRemote();
final List<User> filterUsers = await Future.wait(
usersFromRemote.where((u) => u.name != 'jim').map(
(user) async {
return formatUser(user);
},
),
);
return filterUsers;
}
Or you can use forEach
but which is not very functional.
Upvotes: 1