5

My intention is that i want say 5 instances of an class inside a list

final List<Ball> _ballList =[Ball(),Ball(),Ball(),Ball(),Ball(),]

instead of that I want something like

final List<Ball> _ballList =[Ball() * 5]

2 Answers 2

8

Using generate() should help
For example,

class Ball{
  String color;
}

void main() {
  List<Ball> ballList = new List<Ball>.generate(5,(i)=>Ball());
  for(int i=0;i<ballList.length;i++) {
    print(ballList[i]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

5

With Dart 2.3 or later, you could use collection-for:

final List<Ball> _ballList = [
  for (var i = 0; i < 5; i += 1) Ball(),
];

Note that the above will generate a List with 5 different instances of Ball, which I'm assuming is what you want. In languages (e.g. Python) that support constructs like your [Ball() * 5] example, you'd instead get a list that contains 5 elements of the same instance. If want the same instance instead, then you could use the List.filled constructor:

final List<Ball> _ballList = List<Ball>.filled(5, Ball());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.