1

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

2 Answers 2

2

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.
}
Sign up to request clarification or add additional context in comments.

Comments

2

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 Colors, and all of them are white.

2 Comments

So how would that be in my case? List<Color>.generate(31, (Color i) => i=Colors.white);?
You are on the right path, but the line you suggested won't work because generate will provide you with an index of type int, and not with a color. I should have built an example that was more related to your question. Consider the example I've added to my edited answer, hope it suits your needs.

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.