Dart报The return type ‘bool‘ isn‘t a ‘void‘, as required by the closure‘s context

简介: Dart报The return type ‘bool‘ isn‘t a ‘void‘, as required by the closure‘s context

错误描述

对List使用forEach时报错The return type ‘bool’ isn’t a ‘void’, as required by the closure’s context。

代码如下:

bool _checkData() {
  _myControllers.forEach((element) {
    if(element.text.isEmpty||int.parse(element.text) <= 0){
      return false;
    }
    return true;
  });
}

问题分析:

报错是说返回类型“bool”不是闭包上下文所要求的“void”。在forEach里直接return了一个bool类型,但是forEach要求是不能返回值的。


解决方法

这个错误是因为forEach的回调函数要求返回void,但你的代码中返回了bool。

forEach的回调函数是对每个元素执行某个操作,它本身不应该有返回值。在forEach外部判断所有controller的text是否合法,而不是在回调函数内判断并返回bool。

正确的代码应该是:

bool _checkData() {
  for (var element in _myControllers) {
    if (element.text.isEmpty || int.parse(element.text) <= 0) {
      return false;
    }
  }
  return true;
}
相关文章
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
Error: Element type is invalid: expected a string (for built-in components) or a class/function
2311 0
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
|
5月前
|
编译器
error TS2322 Type ‘string null‘ is not assignable to type ‘string undefined‘.
error TS2322 Type ‘string null‘ is not assignable to type ‘string undefined‘.
91 1
VS2005 error C2864 only static const integral data members can be initialized within a class
VS2005 error C2864 only static const integral data members can be initialized within a class
error : Class declarations lacks Q_OBJECT macro
error : Class declarations lacks Q_OBJECT macro
|
10月前
|
SQL Java 数据库连接
attempted to return null from a method with a primitive return type
attempted to return null from a method with a primitive return type
93 0
|
11月前
|
JSON Android开发 数据格式
Android:解析Json异常 Expected a string but was BEGIN_OBJECT at
今天解析后端数据时,发现了这个报错:Expected BEGIN_OBJECT but was STRING at 看来是自己哪儿解析错误了。 因为数据的特殊性,后端返回的Json串里面可能还会有Json数据,可能嵌套了三次层,
|
11月前
|
JavaScript 前端开发 安全
TypeScripe笔记:any、unknown、never、void、null 和 undefined 及其比较
TypeScripe 中,any、unknown、never、void、null 和 undefined 的比较
113 0
|
Android开发 Kotlin
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
2894 0
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
|
Linux
编译OpenJDK8:error: control reaches end of non-void function [-Werror=return-type]
编译OpenJDK8:error: control reaches end of non-void function [-Werror=return-type]
153 0
TypeError: sequence item 0: expected string, int found
TypeError: sequence item 0: expected string, int found