我正在运行 list.firstWhere
,有时会抛出异常:
Bad State: No element
When the exception was thrown, this was the stack:
#0 _ListBase&Object&ListMixin.firstWhere (dart:collection/list.dart:148:5)
我不明白这意味着什么,也无法通过查看at the source来识别问题。
我的firstWhere
如下:
list.firstWhere((element) => a == b);
答案 0 :(得分:18)
当没有匹配的元素时,即对于a == b
和可选参数{{ 1}} 未指定。
您还可以指定list
来处理这种情况:
orElse
答案 1 :(得分:3)
firstWhere
重新调整根据条件生成的newList
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'),
orElse: () => 'No matching color found');
print(newList);
}
输出:
No matching color found
OR
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('blue'),
orElse: () => 'No matching color found');
print(newList);
}
输出:
blue
如果在代码中未定义orElse,并且错误的项目得到了列表中不存在的搜索,则显示BadStateException
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'));
print(newList);
}
输出:
Uncaught Error: Bad state: No element
答案 2 :(得分:1)
现在您可以导入 package:collection
并使用扩展方法 firstWhereOrNull
import 'package:collection/collection.dart';
void main() {
final myList = [1, 2, 3];
final myElement = myList.firstWhereOrNull((a) => a == 4);
print(myElement); // null
}
答案 3 :(得分:0)
firstWhere()
实现如下所示:
E firstWhere(bool test(E element), {E orElse()?}) {
for (E element in this) {
if (test(element)) return element;
}
if (orElse != null) return orElse();
throw IterableElementError.noElement();
}
因此,如您所见,如果定义了orElse
arg,则该方法将使用该方法,并且如果没有元素与条件匹配,则不会引发任何异常。因此,使用下面的代码来处理错误的情况:
list.firstWhere((element) => a == b, orElse: () => null); // To return null if no elements match
list.firstWhere((element) => a == b, orElse: () => print('No elements matched the condition'));
答案 4 :(得分:0)
在飞镖 2.10
上有一个名为null-safety
的新功能,当您有一系列对象并且想要对某个对象做某事时,它可以为您做魔术对象的属性:
class User {
String name;
int age;
User(this.name, this.age);
@override
String toString() {
return 'name:$name, age:$age';
}
}
void main() {
List<User?> users = [User("Ali", 20), User("Mammad", 40)];
print(users.toString()); // -> [name:Ali, age:20, name:Mammad, age:40]
// modify user age who it's name is Ali:
users.firstWhere((element) => element?.name == "Ali")?.age = 30;
print(users.toString()); // -> [name:Ali, age:30, name:Mammad, age:40]
// modify a user that doesn't exist:
users.firstWhere((element) => element?.name == "AliReza", orElse: ()=> null)?.age = 30; // doesn't find and works fine
print(users.toString()); // -> [name:Ali, age:30, name:Mammad, age:40]
}