关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

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

发布时间:2023-06-26 19:00:05

错误描述

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

/template/Home/leiyu/PC/Static