1

The return type of the following function is Future<File?> and yet the compiler does not complain that there is no return value if the picker did not return a picture.

static Future<File?> takeImage() async {
    PickedFile? pickedFile = await ImagePicker().getImage(source: ImageSource.camera);
    if (pickedFile != null) {
      print('PHOTO TAKEN');
      return File(pickedFile.path);
    } else {
      print('NO PHOTO TAKEN');
    }
  }

Would it not make more sense if I had to return null if the picture wasn't taken?

Does a method without a return statement always return null?

The example above seams to suggest it, and something as simple as this compiles too.

static String? s() {}

Could some one clarify whats going on?

Joel Broström
  • 3,530
  • 1
  • 34
  • 61
  • `void` A special type that indicates a value that’s never used. Functions like printInteger() and main() that don’t explicitly return a value have the void return type. – Simon Sot May 27 '21 at 08:48
  • 1
    read carefully [A tour of the Dart language](https://dart.dev/guides/language/language-tour) - section about `Functions` – pskink May 27 '21 at 08:49

2 Answers2

3

Thanks to @pskink for pointing me in the right direction.

Straight from the documentation:

Return values
All functions return a value. If no return value is specified, the statement return null; is implicitly appended to the function body.

Joel Broström
  • 3,530
  • 1
  • 34
  • 61
0

Does a method without a return statement always return null?

Yes, here's a simple example

Future<void> main() async {
  var str = await start();
  print(str);
}

Future<String> start() async {
  await Future.delayed(Duration(seconds: 2));
}

output:

null

Paste it into dartpad to see it work :)

MSpeed
  • 8,153
  • 7
  • 49
  • 61
  • It does not work for me running Dart 2.13.0. It wont compile with the error: The body might complete normally, causing ‘null’ to be returned, but the return type is a potentially non-nullable type. – Joel Broström May 27 '21 at 09:07