Reputation: 69
I wanted to make a list of colors in dart for my app but, since I don't want this list to be enormous, I'd like to know if there's a way to generate a list given a particular condition. The list is this one:
List dateColors = [
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white,
Colors.white
];
Upvotes: 1
Views: 818
Reputation: 8393
If you want to fill a List
with the same value, use filled
:
import 'package:flutter/material.dart';
void main() {
final dateColors = List.filled(31, Colors.white);
print(dateColors);
// [Color(0xffffffff), ..., Color(0xffffffff)], a total of 31 Colors.white.
}
Upvotes: 2
Reputation: 2717
It's funny that you mentioned the key word here: generate
. That's the constructor of the List
type you are looking for.
List<int>.generate(3, (int index) => index * index); // [0, 1, 4]
Check the docs for more info on this constructor.
In your case, you could discard the index that the generate
constructor is giving you, to build a list that is made of the same objects repeating over and over again. Consider this snippet as an example that may suit your needs
import 'package:flutter/material.dart';
void main() {
final colors = List<Color>.generate(20, (_) => Colors.white);
print(colors);
// Prints [Color(0xffffffff), ..., Color(0xffffffff)], a total of twenty Colors.white.
}
you can see that it prints a list of 20 Color
s, and all of them are white.
Upvotes: 2