首先列出错误状态:无元素


82

我正在跑步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)

我不明白这意味着什么,也无法通过查看源来识别问题。

我的firstWhere样子是这样的:

list.firstWhere((element) => a == b);

Answers:


171

当没有匹配的元素就会发生这种情况,即当a == b是从来没有真正用于任何元素list 可选参数orElse没有被指定。

您还可以指定orElse处理以下情况:

list.firstWhere((element) => a == b, orElse: () => print('No matching element.'));

51
list.firstWhere((element) => a == b, orElse: () => null);允许您静默返回null。
Nicolas Perraut

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

要么

 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


1

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'));

1

在dart上,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]

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.