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
2552 0
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
|
Java
Can't convert boolean to string automatically, because the "boolean_format" setting was "true,false"
版权声明:本文为 testcs_dn(微wx笑) 原创文章,非商用自由转载-保持署名-注明出处,谢谢。 https://blog.csdn.net/testcs_dn/article/details/71683167 ...
2459 0
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
|
Android开发 Kotlin
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
3159 0
【错误记录】Kotlin 编译报错 ( Type mismatch: inferred type is String? but String was expected )
|
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
190 0
|
JSON Android开发 数据格式
Android:解析Json异常 Expected a string but was BEGIN_OBJECT at
今天解析后端数据时,发现了这个报错:Expected BEGIN_OBJECT but was STRING at 看来是自己哪儿解析错误了。 因为数据的特殊性,后端返回的Json串里面可能还会有Json数据,可能嵌套了三次层,
|
JavaScript 前端开发 安全
TypeScripe笔记:any、unknown、never、void、null 和 undefined 及其比较
TypeScripe 中,any、unknown、never、void、null 和 undefined 的比较
167 0
|
Python
AttributeError: 'module' object has no attribute 'main'
AttributeError: 'module' object has no attribute 'main'
205 0
AttributeError: 'module' object has no attribute 'main'