0
votes

I am reading over the documentation for Flutter.

On this page, I have observed the following curious method. In the method, the declared return type is Future. The method though, does not have the return keyword present anywhere. Why is this?

Future<void> _incrementCounter() async {
  setState(() {
    _counter++;
  });
  Directory directory = await getApplicationDocumentsDirectory();
  final String dirName = directory.path;
  await File('$dir/counter.txt').writeAsString('$_counter');
}

I have been able to ascertain that all flutter functions return a value, and the default return value is null. But if this method always returns null, then why declare a return type of Future<void>?

2

2 Answers

5
votes

That is because the function is marked with the async modifier:

Future foo() async {
  print('hello world');
}

is equivalent to

Future foo() {
  try {
    print('hello world');
    return Future.value(null);
  } catch (err) {
    return Future.error(err);
  }
}
1
votes

In Dart even-though it's an optionally typed language which means you can omit the type , It's recommended to provide it

When method does not have a return type , return null is appended , So in your example it's fit to return Future.value(null);

please see Default return type in Dart