Dilhan Bhagat
Dilhan Bhagat

Reputation: 498

Flutter : Loop through List

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.

Upvotes: 1

Views: 4965

Answers (2)

RadiantOne
RadiantOne

Reputation: 319

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

Upvotes: 0

user10539074
user10539074

Reputation:

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

Upvotes: 3

Related Questions