12

I'm iOS Developer and new for Flutter. In the Swift language If we want to repeat the same value for a specific time in the Array.

Ex.

If In the Array I want to repeat 0 for 5 times then I can do by one line of code like below.

let fiveZeros = Array(repeating: "0", count: 5)
print(fiveZeros)
// Prints "["0", "0", "0", "0", "0"]"

init(repeating:count:) function used.

So I'm looking for any function or code that works in Flutter.

I do googling but didn't find a solution.

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Govaadiyo
  • 5,644
  • 9
  • 43
  • 72

4 Answers4

21

In dart you can use the filled factory of List.

final list = List.filled(5, 0);
print(list);  //-> [0, 0, 0, 0, 0]

See more in the list docs.

Edman
  • 5,335
  • 29
  • 32
5

Starting from Dart 2.3.0 you can use conditional and loop initializers, so for your case it should be:

var fiveZeros = [for (var i = 0; i < 5; ++i) 0];

Everything becomes much flexible and powerful when you want to initialize by expression, not just constant:

var cubes = [for (var i = 0; i < 5; ++i) i * i * i];

is the same as [0, 1, 8, 27, 64].

Conditional elements are also essential taking into account the possibility to build a list of widgets where some of them depend on the state or platform.

More details here

apc
  • 1,152
  • 12
  • 9
4

You can use the filled method like what @Edman answered. I just want to add one more way by using generate

final list = new List.filled(5, 0);
print(list);

final list1 =  new List.generate(5, (index) {
  return 0;
});
print(list1);
Phuc Tran
  • 7,555
  • 1
  • 39
  • 27
1

Use List.generate method.

var list = List.generate(5, (i) => 'Z');
Vinoth Kumar
  • 12,637
  • 5
  • 32
  • 38