How to flatten a List?

后端 未结 4 1471
生来不讨喜
生来不讨喜 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 01:48

    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

提交回复
热议问题