Dart 查找数组中唯一满足条件的元素,用 singleWhere ,源代码定义如下
E lastWhere(bool test(E element), {E orElse()})返回值为泛型,参数 test 为指定的条件,返回值为 bool,第二个参数 orElse 为可选参数,是当数组中没有满足指定条件的元素设置的自定义值。
例
List<int> l1 = [8, 12, 4, 1, 17, 33, 10]; int a = l1.singleWhere((e) => e > 30); int b = l1.singleWhere((e) => e > 10); int c = l1.singleWhere((e) => e > 10, orElse: () => -1); int d = l1.singleWhere((e) => e > 40, orElse: () => -1); print(a); // 33 print(b); // 报错 print(c); // 报错 print(d); // -1在使用 singleWhere 时,要注意 以下几点
当数组中仅有一个满足条件的元素时,返回该元素当数组中有多个满足条件的元素时,报错当数组中有多个满足条件的元素时,即使设置了 orElse ,也会报错当数组中没有满足条件的元素时,返回 orElse 指定的返回值更多 Dart 中 List 数组的方法,推荐一篇博客 Dart 中 List 数组的常用方法