如何使用“.removeWhere”删除对象名称的一个示例,而不是Flutter中列表中的所有元素

64jmpszr  于 2022-12-05  发布在  Flutter
关注(0)|答案(3)|浏览(131)

例如,假设您有一个苹果列表

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

并且您只想使用.removeWhere删除一个红苹果

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

然而,当我只想删除一个“red”的示例时,这会删除所有“red”的示例!有什么解决方案吗?

piah890a

piah890a1#

您可以直接在列表中使用remove方法:

List<String> apples = ['green', 'red','red', 'yellow'];    
   apples.remove("red");
   print(apples); // [green, red, yellow]
uajslkp6

uajslkp62#

如果你想像使用removeWhere方法一样使用它,你可以使用这个扩展方法:
将它添加到全局作用域(在类之外,将它放在任何需要的地方)

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;
      }
      
    }        
  }
}

然后您可以这样使用它:

List<String> apples = ['green', 'red','red', 'yellow'];    
   apples.removeFirstWhere((element) => element == 'red');
   print(apples); // [green, red, yellow]
ua4mk5z4

ua4mk5z43#

第三种解决方案是,如果你想删除List中的所有示例,使每个String只出现一次,你可以简单地将其设为Set

List<String> apples = ['green', 'red','red', 'yellow', 'green'];
 print(apples.toSet().toList()); // [green, red, yellow]

相关问题