Remove empty lists from a list of lists and flatten it using Dart

If you have a list created using Dart and it contains multiple lists inside it. Some of the lists contain no items and you want to get rid of those empty lists along with flattening the list. We are explaining the methods in Dart to do it.

void main() {
  List listOfLists = [['a', 'b', 'c'], [], ['d', 'e'], [], [], ['f', 'g', 'h'], [], []];

  List result = listOfLists.expand((x) => x).toList();


[a, b, c, d, e, f, g, h]

A Dart List is a collection of elements that can be used to store and access data using the index. The List is a mutable collection means you can use add or remove items from it.

We are using here List.expand() function to flatten a list of lists and remove empty lists for it.

Was this helpful?