Dart| Flutter:列表过滤搜索与实例

4,103 阅读2分钟

本教程展示了在Dart和flutter中用一些逻辑来过滤列表的多个例子

Dart and Flutter Fliter list examples

Dart/flutter过滤对象列表或数组的多种方法

以下是我们可以过滤对象列表的多种方法

在下面的两个例子中,我们有一个对象的列表,其中每个对象都包含工资和名字。

根据工资条件过滤对象的列表,并输出结果。

  • 使用Where predicateList.where() 方法允许你迭代列表并应用谓词函数,并返回一个元素流。toList() 方法从元素流中抽取一个元素追加到列表中,最后,返回元素的列表。

下面是一个示例代码程序

void main() {
  List emps = [
    {"salary": 5000, "name": "john"},
    {"salary": 6000, "name": "andre"},
    {"salary": 8000, "name": "mark"},
    {"salary": 11000, "name": "flint"}
  ];
  List result = emps.where((o) => o['salary'] > 10000).toList();

  print(result);
}

输出:

[{salary: 11000, name: flint}]
  • 使用for-in循环

这是为了循环迭代对象的列表,条件也被添加在里面,并返回对象。

void main() {
  List emps = [
    {"salary": 5000, "name": "john"},
    {"salary": 6000, "name": "andre"},
    {"salary": 8000, "name": "mark"},
    {"salary": 11000, "name": "flint"}
  ];
  var result = [
    for (var emp in emps)
      if (emp["salary"] > 7000) emp
  ];

  print(result);
}

输出:

[{salary: 8000, name: mark}, {salary: 11000, name: flint}]

基于字符串的第一个字母的列表过滤器

这个例子用条件过滤字符串列表,列表中的字符串以一个字母为首,这个例子使用List.where() ,基于条件谓词。

void main() {
  var words = ['one', 'two', 'three'];
  List<String> result = words.where((f) => f.startsWith('t')).toList();
  print(result);
}

输出:

[two, three]

基于小于数值的数字的Dart列表过滤器

创建一个数字的列表。

你想过滤大于100的数字。这个例子在条件谓词的基础上使用List.where()

void main() {
  var numbers = [11, 34, 35, 150, 20, 200];
  List<int> numberResult = numbers.where((f) => f > 100).toList();
  print(numberResult);
}

输出:

[150, 200]

基于空值的Dart列表过滤器

我们有两种方法可以做到这一点。

一种方法是突变原始列表或数组,使用removeWhere 方法包含的函数参数,检查空值并将其从原始列表中删除。

void main() {
  var words = ['one', null, 'three', "four"];
  words.removeWhere((value) => value == null);
  print(words); //[one, three, four]

}

另一种方法是不修改原始列表,而是创建一个新的数组,其中包含被删除的值。

使用where 函数检查非空值,最后返回空值。

void main() {
  var words = ['one', null, 'three', "four"];
  List result = words.where((value) => value != null).toList();
  print(result);
}

输出:

[one, three, four]

结论

这篇文章展示了如何用多种方法和例子来过滤和搜索列表