How can I create multiple objects in 1 Step in Dart? Something like:

Class Player{ 

var Health;
var Level; .... }

Somewhere else:

Player[] player = new Player[20];

How can I do that in Dart?


Solution 1: Mazin Ibrahim

You can create a list of Player using the following line:

     List<Player> player = new List(20);

And then initialize each object of your player list :

     for (var i in jsonResponse['participants']) {
       player[x] = new Player() ; // add this to your code
       var fill = player[x];
       fill.health = i['health'];
       x++;
     }

You can find more information about the proper way of building and initializing list in the official Dart Documentation.


Solution 2: Dyego Vieira

If you wanna create a lot "Players"... Try this:

var players = List.generate(20, (i) => Player(/* properties */));

Filling in from any source, you can use the "i" as the index.

var players = List.generate(20, (i) { 
    var sourceRef = source[i];

    return Player(
      health: sourceRef["health"]
    ); 
});