O'Reilly logo

Dart: Scalable Application Development by Ivo Balbaert, Sergey Akopkokhyants, Davy Mitchell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Flattening a list

A list can contain other lists as elements. This is effectively a two-dimensional list or array. Flattening means making a single list with all sublist items contained in it. Take a look at the different possibilities in flatten_list.dart.

How to do it...

We show three ways to flatten a list in the following code:

List lst = [[1.5, 3.14, 45.3], ['m', 'pi', '7'], [true, false, true]];
// flattening lst must give the following resulting List flat:
// [1.5, 3.14, 45.3, m, pi, 7, true, false, true]

void main() {
  // 1- using forEach and addAll:
  var flat = [];
  lst.forEach((e) => flat.addAll(e));
  print(flat);
  // 2- using Iterable.expand:
  flat = lst.expand((i) => i).toList();
  // 3- more nesting levels, work recursively: lst = [[1.5, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required