With Dart 2.3 or later, you instead can use collection-for
and the spread operator to easily flatten a list. I personally find it to be more readable than using Iterable.expand
:
List<T> flatten<T>(Iterable<Iterable<T>> list) =>
[for (var sublist in list) ...sublist];
void main() {
var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];
var b = flatten(a);
print(b); // Prints: [1, 2, 3, a, b, c, true, false, true]
}
If there are nested lists that you need to recursively flatten, you could use:
List<T> flattenDeep<T>(Iterable<dynamic> list) => [
for (var element in list)
if (element is! Iterable) element else ...flattenDeep(element),
];
void main() {
var a = [[1, [[2], 3]], [[['a']], 'b', 'c'], [true, false, [true]]];
var b = flattenDeep(a);
print(b) // Prints: [1, 2, 3, a, b, c, true, false, true]
}
package:collection
additionally now provides a flattened
extension method that can flatten one level of nesting:
import 'package:collection/collection.dart';
void main() {
var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];
var b = a.flattened.toList();
print(b); // Prints: [1, 2, 3, a, b, c, true, false, true]
}