Does a function without a return statement always return null in Flutter?

1.8k views Asked by At

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?

2

There are 2 answers

0
Joel Broström On BEST ANSWER

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.

1
MSpeed On

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 :)