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
.
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, 3.14, 45.3], ['m', 'pi', '7'], "Dart", [true, false, true]]; print(flatten(lst)); }
The simplest method uses a combination of forEach
and addAll
. The second method uses the fact that List
implements Iterable
, and so has the expand
method. The expand
method is used here with an identity function as its argument; every element is returned without applying a function.
Using expand
does not work if the list contains ints
(or Strings
, doubles
, and so on) as single list elements, or if there are multiple levels of nesting. In that case, we will have to work recursively, as implemented in the flatten
method:
Iterable flatten(Iterable iterable) => iterable.expand((e) => e is List ? flatten(e) : [e]);