16

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.

4
  • Can you share the use case where you need this repeating function? Commented May 30, 2018 at 7:01
  • actually I'm just making demo app for larnning purpose where I want to do select and unselect ListTile Commented May 30, 2018 at 7:04
  • I'm voting to close this question as off-topic because we can easily find answer from official document of the Flutter. Commented Jun 3, 2018 at 5:30
  • I think you should keep it, this is still useful for new developer Commented Jun 3, 2018 at 8:52

4 Answers 4

25

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.

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

1 Comment

Yeah! got expected output. Thanks for improving my knowledge.
5

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);

Comments

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

Comments

2

Use List.generate method.

var list = List.generate(5, (i) => 'Z');

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.