How to Initialize the List with the same element in flutter dart?

You can try like this

List<int>.generate(4, (int index) => 5);

For more, read this


The easiest way I can think of is List.filled:

List.filled(int length, E fill, { bool growable: false }).

The params would be:

  • length - the number of elements in the list
  • E fill - what element should be contained in the list
  • growable - if you want to have a dynamic length;

So you could have:

List<int> zeros = List.filled(10, 0)

This would create a list with ten zeros in it.

One think you need to pay attention is if you're using objects to initialise the list for example:

SomeObject a = SomeObject();
List<SomeObject> objects = List.filled(10, a);

The list created above will have the same instance of object a on all positions.


If you want to have new objects on each position you could use List.generate:

List.generate(int length, E generator(int index), {bool growable:true})

Something like:

List<SomeObject> objects = List<SomeObject>.generate(10, (index) => SomeObject(index);

OR:

List<SomeObject> objects = List<SomeObject>.generate(10, (index) { 
      SomeOjbect obj = SomeObject(index)
      obj.id= index;
      return obj;
});

This will create a new instance for each position in list. The way you initialise the object is up to you.

Tags:

List

Dart

Flutter