1

I am trying to loop through a list of colours. When the loop reaches the end I would like it to restart or go to the beginning of the list. Can someone help me I am new to Dart and flutter. Much appreciated!!! Thanks in advance.

List<Color> color = ['Red', 'yellow', 'pink', 'blue'];

So when it gets to blue , I'd like it to go back to Red is that possible. Please help.

2 Answers 2

3

as an option:

void main() {
  List<String> color = ['Red', 'yellow', 'pink', 'blue'];

  for (int i = 0; i < 10; i++) {
    print(color[i % color.length]);
  }
}

or you can write an extension for List like this:

void main() {
  List<String> color = ['Red', 'yellow', 'pink', 'blue'];

  for (int i = 0; i < 10; i++) {
    print(color.getElement(i));
  }
}

extension EndlessElements<T> on List<T> {
  T getElement(int index) {
    return this[index >= this.length ? index % this.length : index];
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a while loop and get the index in the list by using the remainder.

Not sure what your use case is, but if you are calling it in a builder or something you can just use index%4 to pick a color.

List<Colour> color = ['Red', 'yellow', 'pink', 'blue'];

  int count = 0;

  while(count < 8){
    print(color[count%4]);
    count = count + 1;
  }

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.