Reputation: 6786
I've two arrays/Lists:
users =[object1,object2,object3]; all of the same type: Class User
teams =[object1,object2,object3]; all of the same type: Class Team
I want to create a new array dynamically containing objects of type SupportTeams which has properties of type User and Team.
I think I should use the map operator to convert the arrays to my new array.
Something like this
List<SupportTeams> combiner(List<User> users, List<Team> teams) {
return users.map((user) {
teams.map((team) {
SupportTeams(user,team);
});
}).toList();
}
Upvotes: 0
Views: 30
Reputation: 3219
You're almost there. First thing's first, you need to return from your calls within map
:
List<SupportTeams> combiner(List<User> users, List<Team> teams) {
return users.map((user) {
return teams.map((team) {
return SupportTeams(user,team);
});
}).toList();
}
However, this still won't work 100% as you'll have a list of lists. You'll need to flatten the result using expand
:
List<SupportTeams> combiner(List<User> users, List<Team> teams) {
return users.map((user) {
return teams.map((team) {
return SupportTeams(user,team);
});
}).expand((i) => i).toList();
}
If you want to be even more concise, you can use =>
notation instead of returns:
List<SupportTeams> combiner(List<User> users, List<Team> teams) =>
users.map((user) =>
teams.map((team) =>
SupportTeams(user,team))).expand((i) => i).toList();
Finally, as @lrn pointed out in the comments you can use control flow collections to do this much more cleanly:
List<SupportTeams> combiner(List<User> users, List<Team> teams) => [
for (var user in users)
for (var team in teams)
SupportTeams(user, team)
];
Upvotes: 2