Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

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?

like image 971
rahul Kushwaha Avatar asked Nov 29 '19 11:11

rahul Kushwaha


People also ask

How do I create a fixed size list in Flutter?

You can use List. generate to create a list with a fixed length and a new object at each position.

How do you make a list growable in Flutter?

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.


2 Answers

The easiest way I can think of is: 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(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.

like image 57
danypata Avatar answered Sep 28 '22 08:09

danypata


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.

like image 33
Suragch Avatar answered Sep 28 '22 10:09

Suragch