Zzz
Zzz

Reputation: 229

How to remove one instance of an object name with ".removeWhere" instead of all the elements in a list in Flutter

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?

Upvotes: 0

Views: 41

Answers (3)

Gwhyyy
Gwhyyy

Reputation: 9166

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]

Upvotes: 1

Gwhyyy
Gwhyyy

Reputation: 9166

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]

Upvotes: 1

Gwhyyy
Gwhyyy

Reputation: 9166

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]

Upvotes: 1

Related Questions