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

2023-11-19

错误描述

对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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Dart报The return type ‘bool‘ isn‘t a ‘void‘, as required by the closure‘s context 的相关文章

随机推荐