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?
You can use List. generate to create a list with a fixed length and a new object at each position.
To add data to the growable list, use operator[]=, add or addAll. To check whether, and where, the element is in the list, use indexOf or lastIndexOf. To remove an element from the growable list, use remove, removeAt, removeLast, removeRange or removeWhere.
The easiest way I can think of is: List.filled(int length, E fill, { bool growable: false })
.
The params would be:
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(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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With