How can I easily flatten a List in Dart?
For example:
var a = [[1, 2, 3], [\'a\', \'b\', \'c\']
the solution with expand method fits good to satisfy this case :
expect(ListTools.getFlatList([[1],["hello",2],["test"]]),orderedEquals([1,"hello",2,"test"]));
But not for theses ones
expect(ListTools.getFlatList([[1],["hello",2,["foo",5]],["test"]]),orderedEquals([1,"hello",2,"foo",5,"test"]));
expect(ListTools.getFlatList([1,["hello",2],"test"]),orderedEquals([1,"hello",2,"test"]));
To satisfy theses test cases, you need something more recursive like the following function :
List getFlatList(List list) {
List internalList = new List();
list.forEach((e) {
if (e is List) {
internalList.addAll(getFlatList(e));
} else {
internalList.add(e);
}
});
return internalList;
}
Best regards,
Sébastien