0

I'm developing my first application with Dart, which had previously created in JavaScript. In my statement in JavaScript I have declared a List, and I assign values ​​to the first three positions, as seen here:

serpF var = new List ();
serpF [0] = 10;
serpF [1] = 10;
serpF [2] = 10;

How I can do the same in Dart? I have read the documentation of Lists and Arrays of Seth Ladd in "http://blog.sethladd.com/2011/12/lists-and-arrays-in-dart.html" and I've tried everything, but it is being impossible.

Cœur
  • 37,241
  • 25
  • 195
  • 267
yiara
  • 3
  • 1

3 Answers3

2

The javaScript code does not work in Dart because it is an error to access past the end of the List. Dart is like many other languages as this is a way to catch logic errors.

What you can do is add elements to a List:

var serpF = new List();  // This list has length == 0.
serpF.add(10);
serpF.add(10);
serpF.add(10);

You can use method cascades to shorten the code:

var serfP = [];
serpF..add(10)..add(10)..add(10);

If you do know the length, you might also try one of the other List constructors:

var serfP = new List.filled(3, 10);
var serfP = new List.generate(3, (i) => 10);
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
Stephen
  • 471
  • 2
  • 4
2

I addition to what Stephen suggests you can also do:

var serpF = [10, 10, 10];

or

var serpF = new List();
serpF.length = 3;
serpF[0] = 10;
serpF[1] = 10;
serpF[2] = 10;
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
Florian Loitsch
  • 7,698
  • 25
  • 30
1

You can also use the List.generate() constructor:

var list = new List.generate(3, (_) => 10, growable: true);
print(list); // Prints [10, 10, 10].

The first arg specifies the number of elements in the list, the second arg takes a callback to give each element a value, and the third arg ensures that the list is not fixed-width.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51