Hkm Sadek
Hkm Sadek

Reputation: 3209

dart how to assign list into a new list variable

I am trying to extend a list just by using add method like this

List<String> mylists = ['a', 'b', 'c'];
var d = mylists.add('d');
print(d);

It gives error This expression has type 'void' and can't be used. print(d);

Why i cannot save the list in a new variable? Thank you

Upvotes: 2

Views: 5109

Answers (2)

Mangaldeep Pannu
Mangaldeep Pannu

Reputation: 3987

Refering Dart docs: https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html

The add method of List class has return type of void.
So you were unable to assign var d.

To save list in new variable use:

List<String> mylists = ['a', 'b', 'c'];
mylists.add('d');
var d = mylists;
print(d);

First add the new String i.e. 'd'
And then assign it to new variable

Upvotes: 1

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76263

mylists.add('d') will add the argument to the original list.

If you want to create a new list you have several possibilities:

List<String> mylists = ['a', 'b', 'c'];

// with the constructor
var l1 = List.from(mylists);
l1.add('d');

// with .toList()
var l2 = mylists.toList();
l2.add('d');

// with cascade as one liner
var l3 = List.from(mylists)..add('d');
var l4 = mylists.toList()..add('d');

// in a upcoming version of dart with spread (not yet available)
var l5 = [...myList, 'd'];

Upvotes: 5

Related Questions