THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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]
There are multiple ways we can do list flattening.
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]
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]
To summarize, Learned multiple ways to flatten a list of list examples.
🧮 Tags
Recent posts
Nodejs package.json resolutions How to find Operating System username in NodeJS? How to convert Double to Integer or Integer to double in Dart| Flutter By Example Ways to skip test case execution in Gradle project build Learn Gradle | tutorials, and examplesRelated posts