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;
}

猜你喜欢

转载自blog.csdn.net/yikezhuixun/article/details/130539200