{

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 the 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 flatten.

  • 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 for 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.

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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example