dart modulo operator circular list

I want to use the modulo (%) operator in order to access to list items in a circular way. But the code below doesn't work:

void main() {
  List<String> myList = ['one', 'two', 'three', 'four'];
  int currIdx = 0;
  
  for (int i = 0;i < 10;i++) {
    print(myList[currIdx]);
    currIdx = currIdx++ % myList.length;
  }
}

enter image description here

1 answer

  • answered 2022-05-07 05:17 Jean-Pierre Schnyder

    Here's the solution: instead of coding

    currIdx++
    

    you must code

    ++currIdx
    

    Complete code:

    void main() {
      List<String> myList = ['one', 'two', 'three', 'four'];
      int currIdx = 0;
      
      for (int i = 0;i < 10;i++) {
        print(myList[currIdx]);
        currIdx = ++currIdx % myList.length;
      }
    }
    

    enter image description here

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum