Is it possible to use destructure and spread in a list with dart like javascript in dart?

Viewed 6372

I have been playing around with flutter for a few days now, haven't gotten a hang of it. While trying out the dart and its methods it got me thinking to make the learning curve easier started relating javascript (as I am very familiar with it, personal choice, people might have or use different approach).

I am stuck with this one small doubt, is it possible to destructure and spread at the same time in dart? I understand if it's not possible, how would I achieve something like this with dart? I am trying to get the first item of the array in a variable and the rest of the array values in a string with joining them as a string. Do I have to loop through all of them? Can't be in a shorter or prettier way(perspective tho)?

// JavaScript
var someArray = ['1', '2' ,'3', '4'];
var [first, ...rest] = someArray;
var restAsString = rest.join(' ');
console.log(first); // 1
console.log(restAsString); // 2 3 4
//dart
main(List<String> arguments) {
  List<String> someList = ['1', '2' ,'3', '4'];
  String restString = '';
  String firstString = '';
  for (int i = 0; i < someList.length; i++) {
    if(i == 0 ) {
      firstString = someList[i];
    } else {
      restString = '$restString ${someList[i]}';
    }

  }
  print(firstString); // 1
  print(restString);  // 2 3 4
}
2 Answers

The following solution mutates the original list, but accomplishes your goal.

List<String> someList = ['1', '2', '3', '4'];

final String firstString = someList.removeAt(0);
final String restString = someList.join(' ');

print(firstString); // 1
print(restString); // 2 3 4

To do this without changing the original list you could write:

  var someList = <String>['1', '2', '3', '4'];
  assert(someList.length > 0);
  print(someList[0]);
  print(someList.sublist(1).join(' '));
Related