{

Dart| Flutter How to: Flatten a List with examples


Flatten a List in Dart and Flutter

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.

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 convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not