forEach当返回值时在函数中使用项目的循环时,我收到以下错误。
bool validatedValues(List<String> values){
values.forEach((i){
if (i.length > 3){
return true;
}
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
我使用 dart null safety sdk 版本:">=2.12.0 <3.0.0"
完整错误:
The return type 'bool' isn't a 'void', as required by the closure's context.dartreturn_of_invalid_type_from_closure
Run Code Online (Sandbox Code Playgroud)
Thi*_*rry 15
该问题是由return true您的内部引起的forEach。forEach正在等待 avoid Function(T)不是 a bool Function(T)。
我认为你试图实现的目标是:
bool validatedValues(List<String> values){
bool result = false;
values.forEach((i){
if (i.length > 3){
result = true;
}
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
或者,可能更优雅:
bool validatedValues(List<String> values) => values.any((i) => i.length > 3);
Run Code Online (Sandbox Code Playgroud)
bool any(bool test(E element));
true如果列表中至少一项通过 验证,则返回此值test。参考
bool every(bool test(E element));
true如果列表中的所有项目都经过验证,则返回此值func。参考
| 归档时间: |
|
| 查看次数: |
28453 次 |
| 最近记录: |