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
2571 0
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
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
|
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
224 0
|
JavaScript 前端开发 安全
TypeScripe笔记:any、unknown、never、void、null 和 undefined 及其比较
TypeScripe 中,any、unknown、never、void、null 和 undefined 的比较
177 0
|
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]
194 0
TypeError: sequence item 0: expected string, int found
TypeError: sequence item 0: expected string, int found
|
Web App开发 JavaScript 前端开发
为什么用 void 0 代替 undefined?
为什么用 void 0 代替 undefined?
515 0
为什么用 void 0 代替 undefined?
|
Android开发 Kotlin
【错误记录】Kotlin 编译报错 ( Not nullable value required to call an ‘iterator()‘ method on for-loop range )
【错误记录】Kotlin 编译报错 ( Not nullable value required to call an ‘iterator()‘ method on for-loop range )
281 0
【错误记录】Kotlin 编译报错 ( Not nullable value required to call an ‘iterator()‘ method on for-loop range )