How to remove a range in list depending on a condition in dart?

Issue

I made a list to separate to different lists of integers for a flutter project.
Now I want to remove all integers after the last null value. How can I do that ?

void main() {
  List<int> v =[];
  for(int i=0; i<3; i++){
    for(int j=0; j<4; j++){
      v.add(1);
    }
    v.add(null);
  }
  for(int i=0; i<12; i++){
    print(v[i]);
  }
}

Solution

You can find the index of the last occurrence of null in the list and make a sublist starting from 0 to that index (+1 is used to include the last null value in the sublist):

  List<int> v2 = v.sublist(0, v.lastIndexOf(null) + 1);
  for(int i=0; i<v2.length; i++){
    print(v2[i]);
  }

Answered By – Mobina

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.