0

I am new to dart/flutter programming. I have been trying to analyze the content of a file and return the result but couldn't. The code actually works when in the main function, but as soon as I take it out it doesn't work anymore. I have read the dart tutorial on futures, async, await, and streams as well as watched YouTube videos but still couldn't solve the problem. I believe my problem revolves around those concepts. Here is my code:

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

I was getting 2 errors:

  1. The function name 'r' was underlined:
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.
  1. The variable 'element' was underlined:
The return type 'String' isn't a 'void', as required by the closure's context.

Thanks.

  • 1
    `forEach` doesn't return anything, and returning a value from its callback won't do anything either. [Prefer using a normal `for` loop](https://stackoverflow.com/a/65420010/). – jamesdlin Jun 18 '21 at 21:15

1 Answers1

0

Your first error says that "Whatever happens, You have to return a String"

Your second error says that you are trying to return a String in a void function, As you see List. Foreach is a void function and you can't just return something in it because the return statement matches with the closest Function

So I rewrited you're code as following

Future<String> r(String name) async {
  try {
    var f = File(name);
    var lines = await f.readAsLines();
    for (var element in lines)
      if (element.contains(RegExp(r'^hello'))) {
        return element;
      }
    return "not found";
  } catch (e) {
    return 'An error occurred: $e';
  }
}

Since you are using File and File.readAsLines I think it would be better to just wrap everything inside a try catch bloc k.

Sajad Abdollahi
  • 1,593
  • 1
  • 7
  • 19