Dart| Flutter How to: Flatten a List with examples
List contains a list of sub-lists or a Map i.e two dimensions list.
Flatten list is to output a single list from a two-dimension list.
Let’s create a list of sub-list or two-dimensional lists in dart.
var list = [
[1, 2, 3],
[4, 5, 6],
[7, 8]
];
A two-dimensional list contains a list of elements, where each element is again a list.
After flatting the list, the result is
[1, 2, 3, 4, 5, 6, 7, 8]
flatten list in dart and flutter?
There are multiple ways we can do list flattening.
- List expand method: In this example, the List expand method expands every element into zero or one of the elements. Finally, call toList() is used to convert a single list.
Here is an example of List flatten using the List Expand method.
void main() {
var list = [
[1, 2, 3],
[4, 5, 6],
[7, 8]
];
var flatList = list.expand((element) => element).toList();
print(list);
print(flatList);
}
Output:
[[1, 2, 3], [4, 5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8]
- use forEach and addAll method:
In this example, Created a empty List forEach
is used to iterate an element in a list and adds the sublist into flatList using the addAll method.
Here is an example
void main() {
var list = [
[1, 2, 3],
[4, 5, 6],
[7, 8]
];
var flatList = [];
list.forEach((e) => flatList.addAll(e));
print(list);
print(flatList);
}
Output:
[[1, 2, 3], [4, 5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8]
Conclusion
To summarize, Learned multiple ways to flatten a list of list examples.