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

Issue

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?

Solution

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.

Answered By – Joel Broström

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *