Home > database >  How to remove one instance of an object name with ".removeWhere" instead of all the elemen
How to remove one instance of an object name with ".removeWhere" instead of all the elemen

Time:11-29

For example, Lets say youu 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?

CodePudding user response:

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]

CodePudding user response:

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]

CodePudding user response:

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]
  • Related