Introduction
Sometimes, we may wish to flatMap a list of lists in Flutter/Dart. In this post, we'll learn how to do it.
How to flatMap a list of lists in Flutter
To flatten a list of lists in Flutter/Dart we can use forEach()
or expand()
method:
Flatten a list of lists in Flutter using forEach()
method
var listOfLists = [[1, 2], [3, 4], [5, 6]];
var flatten = [];
listOfLists.forEach((nums) => nums.forEach((number) => flatten.add(number)));
print(flatten);
The output:
[1, 2, 3, 4, 5, 6]
Flatten a list of lists using expand()
method
var listOfLists = [[1, 2], [3, 4], [5, 6]];
var flatten = listOfLists.expand((number) => number).toList();
print(flatten);
The output:
[1, 2, 3, 4, 5, 6]
Conclusion
In this article, we showed how to flatMap
a list of lists in Flutter/Dart.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}