How do I combine two lists in Dart?

前端 未结 8 771
有刺的猬
有刺的猬 2021-01-31 00:46

I was wondering if there was an easy way to concatenate two lists in dart to create a brand new list object. I couldn\'t find anything and something like this:

My list:

8条回答
  •  悲&欢浪女
    2021-01-31 01:44

    addAll is the most common way to merge two lists.

    But to concatenate list of lists, you can use any of these three functions (examples below):

    • expand - Expands each element of an Iterable into zero or more elements,
    • fold - Reduces a collection to a single value by iteratively combining each element of the collection with an existing value,
    • reduce - Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
    void main() {
      List a = [1,2,3];
      List b = [4,5];
      List c = [6];
      List> abc = [a,b,c]; // list of lists: [ [1,2,3], [4,5], [6] ]
      List ints = abc.expand((x) => x).toList();
      List ints2 = abc.reduce((list1,list2) => list1 + list2);
      List ints3 = abc.fold([], (prev, curr) => prev + curr); // initial value is []
      print(ints);  // [1,2,3,4,5,6]
      print(ints2); // [1,2,3,4,5,6]
      print(ints3); // [1,2,3,4,5,6]
    }
    

提交回复
热议问题