23

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?

3 Answers 3

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

that's the problem I want to initialise the object? is there any way to create same object multiple times?
while generating how to refer to this object which is being generated? will this keyword works?
5

You can try like this

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

For more, read this

Comments

5

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.