skip to Main Content

For example,
Lets say you have a list of apples

List<String> apples = ['green', 'red','red', 'yellow']

And you want to remove just one red apple using .removeWhere

apples.removeWhere((element => element == 'red));

however, this removes all instances of ‘red’ when I only want to remove one of them! Any solutions?

3

Answers


  1. you could use directly the remove method on your list:

       List<String> apples = ['green', 'red','red', 'yellow'];    
       apples.remove("red");
       print(apples); // [green, red, yellow]
    
    Login or Signup to reply.
  2. And if you want to use it like you’re using the removeWhere method, you can use this extension method :

    Add this on the global scope (outside your classes, just put it anywhere else you want)

    extension RemoveFirstWhereExt<T> on List<T> {
      void removeFirstWhere(bool Function(T) fn) {
        bool didFoundFirstMatch = false;
        for(int index = 0; index < length; index +=1) {
          T current = this[index];
          if(fn(current) && !didFoundFirstMatch) {
            didFoundFirstMatch = true;
            remove(current);
            continue;
          }
          
        }        
      }
    }
    

    Then you can use it like this:

       List<String> apples = ['green', 'red','red', 'yellow'];    
       apples.removeFirstWhere((element) => element == 'red');
       print(apples); // [green, red, yellow]
    
    Login or Signup to reply.
  3. A third solution, if you want to remove all occurrences in your List so every String should be there only once, you can simply make it a Set :

     List<String> apples = ['green', 'red','red', 'yellow', 'green'];
     print(apples.toSet().toList()); // [green, red, yellow]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search