ZetCode

Dart 谓词

最后修改日期:2024 年 1 月 28 日

在本文中,我们将展示如何在 Dart 中使用谓词。

谓词

谓词的通用含义是指一个陈述,该陈述是真或假。在编程中,谓词是返回布尔值的单参数函数。

Dart 谓词示例

下面的示例是一个简单的谓词示例。

main.dart
bool isPositive(int e) {
  return e > 0;
}

void main() {
  final nums = <int>[0, -1, -2, -4, 5, 3, 6, -8];

  final filtered = nums.where((e) => isPositive(e));
  print(filtered);
}

在程序中,isPositive 谓词用于过滤掉正值。

bool isPositive(int e) {
    return e > 0;
}

isPositive 谓词对所有大于零的值返回 true。

final filtered = nums.where((e) => isPositive(e));

将谓词传递给 where 函数,该函数返回所有满足谓词的元素。

$ dart main.dart
(5, 3, 6)

Dart 匿名谓词

下一个示例将匿名谓词函数传递给 where 函数。

main.dart
void main() {
  final nums = <int>[0, -1, -2, -4, 5, 3, 6, -8];

  final filtered = nums.where((e) => e < 0);
  print(filtered);
}

通常没有必要给函数命名。我们可以直接传递一个匿名函数。

final filtered = nums.where((e) => e < 0);

通过匿名函数,我们过滤掉所有负值。

$ dart main.dart 
(-1, -2, -4, -8)

Dart 谓词与 any

any 函数检查集合中的任何元素是否满足给定的谓词。

main.dart
void main() {
  final nums = <int>[0, -1, -2, -4, 5, 3, 6, -8];

  bool isAny = nums.any((e) => e > 0);
  
  if (isAny) {
    print("There is at least one positive value");
  } else {
    print("There are no positive values");
  }
}

在示例中,我们找出是否有任何正值。

$ dart main.dart 
There is at least one positive value

Dart 谓词与 removeWhere

removeWhere 函数会从集合中移除所有满足给定谓词的元素。

main.dart
void main() {
  final words = <String>['sky', 'blue', 'cup', 'nice', 'top', 'cloud'];

  words.removeWhere((e) => e.length != 3);
  print(words);
}

我们有一个字符串列表。我们移除所有长度不为 3 的字符串。

$ dart main.dart 
[sky, cup, top]

Dart 谓词多条件

以下示例使用带有两个条件的谓词。

main.dart
class Country {
  String name;
  int population;

  Country(this.name, this.population);
  String toString() {
    return "$name $population";
  }
}

void main() {
  final countries = <Country>[
    Country("Iran", 80840713),
    Country("Hungary", 9845000),
    Country("Poland", 38485000),
    Country("India", 1342512000),
    Country("Latvia", 1978000),
    Country("Vietnam", 95261000),
    Country("Sweden", 9967000),
    Country("Iceland", 337600),
    Country("Israel", 8622000)
  ];

  final filtered =
      countries.where((e) => e.name.startsWith("I") && e.population > 10000000);
  print(filtered);
}

我们创建一个国家/地区列表。 我们找到所有以“I”开头且人口超过一百万的国家/地区。

final filtered =
    countries.where((e) => e.name.startsWith("I") && e.population > 10000000);

两个匿名谓词与 && 运算符结合使用。

$ dart main.dart 
(Iran 80840713, India 1342512000)

来源

Dart List - 语言参考

在本文中,我们介绍了 Dart 中的谓词。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有超过十年的经验。

列出 所有 Dart 教程