skip to Main Content

DartPad ScreenShot

I want to delete items one by one from a List.

I could also clear the whole List by using the clear() method but I don’t want that.

If someone has a solution to this problem please point it out.

Thank you.

void main(){
 
  List<String> list =['first','second','3rd','4th','5th'];

  list.removeAt(0);
  list.removeAt(1);
  list.removeAt(2);
  list.removeAt(3);
  list.removeAt(4);

  
  print(list);
//   I don't want to clear all list at once
//   I want to remove one by one element from the list
//   list.clear();
//   list.map((e){
   
//   }).toList();
}

3

Answers


  1. When you remove first 3 element, you do not have 3th element anymore. You can just

      list.removeAt(0);
      list.removeAt(0);
      list.removeAt(0);
      list.removeAt(0);
      list.removeAt(0);
    

    or

      list.removeAt(4);
      list.removeAt(3);
      list.removeAt(2);
      list.removeAt(1);
      list.removeAt(0);
    
    Login or Signup to reply.
  2. When you remove first 3 elements you don’t have 3th element anymore. To make it dynamic to the list length you can do it like so:

        void main() {
          List<String> list = ['first','second','3rd','4th','5th'];
          int length = list.length;
          for (int i = 0; i < length; i++) {
            list.removeAt(0);
          }
          print(list);
        }
    
    Login or Signup to reply.
  3. When you debug it yourself with simple print statements, it will become obvious, what happens:

    void main(){
     
      List<String> list =['first','second','3rd','4th','5th'];
    
      print(list);
      
      list.removeAt(0);
      
      print(list);
      
      list.removeAt(1);
      
      print(list);
      
      list.removeAt(2);
      
      print(list);
      
      list.removeAt(3);
      
      print(list);
      
      list.removeAt(4);
      
      print(list);
    }
    

    [first, second, 3rd, 4th, 5th]

    Removing the first element of this list:

    [second, 3rd, 4th, 5th]

    Removing the second element of that list:

    [second, 4th, 5th]

    Removing the third element of that list:

    [second, 4th]

    And finally, trying to remove the fourth element of a list that no longer has four elements:

    Uncaught Error: RangeError: Value not in range: 3

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search