{

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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example