skip to Main Content

I need the items inside a for to have an action with the exception of the last one, which will have a different action

an example that DOESN’T WORK:

for (var i = 0; i < 10; i++) {
  print('1 - 9');


  if (i.last) {
    print('last item');
  }
}

4

Answers


  1. Try this:

    for (var i = 0; i < 10; i++) {
      print('0 - 8');
    
      if (i == 9) {
        print('last item');
      }
    }
    
    Login or Signup to reply.
  2. you can try this

    for (var i = 0; i < 10; i++) {
     print('1 - 9');
    
    
     if (i==9) {
        print('last item');
        throw Exception("Your message");
     }
     }
    
    Login or Signup to reply.
  3. This is also possible, you can just paste the snippet in DartPad and play with it

    void main() {
      try {
        for (var i = 0; i < 10; i++) {
          if (i == 3) {
            print('item $i');
            throw 'customError';
          } else {
            print('item $i');
          }
        }
      } catch (e) {
        if (e == 'customError') {
          print('You caught your custom error n $e');
        } else {
          print('You caught some other error');
        }
      }
    }
    

    Hope that will help

    Login or Signup to reply.
  4. You can put method in the condition part of the for loop. Here is such example:

    void main() {
      const limit = 10;
      for(int i =0 ;
          () {
            if(i < limit && i < limit-1) {
              doActionA(i);
              return true;
            }
            else if(i < limit){
              doActionB(i);
              return true;
            }
            return false;
          }()
          
          ; i++);
    }
    
    void doActionA(int i){
      print('Not last $i');
    }
    
    void doActionB(int i) {
      print('last $i');
    }
    

    output

    Not last 0
    Not last 1
    Not last 2
    Not last 3
    Not last 4
    Not last 5
    Not last 6
    Not last 7
    Not last 8
    last 9
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search