2

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

Hkm Sadek
  • 2,987
  • 9
  • 43
  • 95
  • You are trying to assign the result of add to a new variable. `add()` alters the existing list. You could just reassign `mylists` to `d` but this would create a reference. If you want a copy(aka keep the old one) look [here](https://stackoverflow.com/questions/21744480/clone-a-list-map-or-set-in-dart) – DTul Apr 01 '19 at 12:19

2 Answers2

5

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'];
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
1

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

Mangaldeep Pannu
  • 3,738
  • 2
  • 26
  • 45