is there any way to spread a array in dart like we do in javaScript?

Viewed 3366

i have array that holds arguments which i want to pass to a constructor of a class

void main() {    
    var arr = ["abc", "bca"];
    A(...arr); //something like that
}

class A {
    String a;
    String b;
    A(this.a,this.b);
}

is there any way to do so. Please help me if you have any solution.

2 Answers

No, Dart doesn't support such a feature for now (Dart-2.1).

To avoid destructuring array at every call sites with A(arr[0], arr[1]) you can add an other constructor.

void main() {    
  var arr = ["abc", "bca"];
  A.spread(arr);
}
class A {
  String a;
  String b;
  A(this.a,this.b);
  A.spread(List arr) : this(arr[0], arr[1]);
}

As there is no destructing in Dart, I simply do this:

var yourList: List<String> = ["first", "second", "third", etc];
var first = yourList.first;
var others = yourList.sublist(1);
Related