How to flatten a List?

后端 未结 4 1474
生来不讨喜
生来不讨喜 2020-12-09 01:36

How can I easily flatten a List in Dart?

For example:

var a = [[1, 2, 3], [\'a\', \'b\', \'c\']         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 02:02

    The easiest way I know of is to use Iterable.expand() with an identity function. expand() takes each element of an Iterable, performs a function on it that returns an iterable (the "expand" part), and then concatenates the results. In other languages it may be known as flatMap.

    So by using an identity function, expand will just concatenate the items. If you really want a List, then use toList().

    var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];
    var flat = a.expand((i) => i).toList();
    

提交回复
热议问题