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

I have a list in dart I want to initialize the list with n number of the same element. example:- initialize the integer list with element 5 4 times. List<int> temp = [5,5,5,5]; what are different ways to initialize the list in dart flutter?



Solution 1:[1]

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.

Solution 2:[2]

You can try like this

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

For more, read this

Solution 3:[3]

Here is a simplified version of the accepted answer. You can use a list literal, a filled list, or a generated list:

final literal = [5, 5, 5, 5];
final filled = List.filled(4, 5);
final generated = List.generate(4, (index) => 5);

print(literal);   // [5, 5, 5, 5]
print(filled);    // [5, 5, 5, 5]
print(generated); // [5, 5, 5, 5]

When you just want to fill the list with the same values, List.filled is good. Unless you literally want [5, 5, 5, 5]. In that case, just use the list literal. It's easy to read and understand.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Augustin R
Solution 2
Solution 3 Suragch