【发布时间】:2021-09-03 12:48:14
【问题描述】:
我是 dart/flutter 编程的新手。我一直在尝试分析文件的内容并返回结果但不能。该代码实际上在 main 函数中有效,但是一旦我将其取出,它就不再有效了。我已经阅读了有关 futures、async、await 和流的 dart 教程以及观看了 YouTube 视频,但仍然无法解决问题。我相信我的问题围绕着这些概念。这是我的代码:
Future<String> r(String name) async {
var f = File(name);
var lines = f.readAsLines();
await lines
.then((line) => line.forEach((element) {
if (element.contains(RegExp(r'^hello'))) {
return element;
}
}))
.onError((error, stackTrace) => 'An error occured');
}
我遇到了 2 个错误:
- 函数名“r”有下划线:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
- 变量“元素”有下划线:
The return type 'String' isn't a 'void', as required by the closure's context.
谢谢。
【问题讨论】:
-
forEach不会返回任何内容,并且从其回调中返回值也不会做任何事情。 Prefer using a normalforloop. -
@jamesdlin。太感谢了。这很有帮助。
标签: flutter dart asynchronous stream future