当我尝试使用List.firstWhere并将orElse
设置为返回null时出错
错误显示:The return type 'Null' isn't a 'City', as required by the closure's context
下面的示例代码
/// city.dart
class City {
final int id;
final String no;
final String name;
final String website;
final bool status;
City(this.id, this.no, this.name, this.website, this.status);
City.fromJson(Map<String, dynamic> json)
: id = json['id'],
no = json['no'],
name = json['name'],
website = json['website'],
status = json['status'];
Map<String, dynamic> toJson() =>
{'id': id, 'no': no, 'name': name, 'website': website, 'status': status};
}
/// main.dart
/// declare a list variable
List<City> _cities = [];
...
_cities.firstWhere((element) => element.id == 1, orElse: () => null); // error here
虽然我可以在firstWhereOrNull
中使用package:collection
方法,并且不会出现任何错误,但我想知道如何正确地使用firstWhere。
谢谢你帮忙!
发布于 2022-09-16 06:16:06
它的抛出错误,因为您声明列表是non-null
值。
如果我们研究这个函数,我们可以看到它们之间的不同。
就像你看到的,T?默认情况下为空。所以它将返回null。
T? firstWhereOrNull(bool Function(T element) test) {
for (var element in this) {
if (test(element)) return element;
}
return null;
}
orElse
的数据类型如下。由于您声明了List<City>
,这是非空值,所以然后,当您设置函数orElse: () => null
时,它将throw IterableElementError.noElement();
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();
}
但是,如果您声明List<City?>
,则firstWhere中的E
现在是可空值。这样就不会有任何错误。
发布于 2022-09-16 06:16:23
您不能返回null
,因为预计该方法将返回City
类的实例,该实例不是nullable
。
你有两个解决方案:
_cities
列表声明为List<City?>
(可空城市列表)。然后,方法firstWhere
可以返回null
,但是您应该注意null safety
,例如:调用element.时
empty City
,因此在City
类中创建静态字段:。
static const empty = City(
id: 0,
no: '',
name: '',
website: '',
status: false,
);
然后您可以返回这个empty City
。
https://stackoverflow.com/questions/73740468
复制相似问题