Does a function without a return statement always return null in Flutter?
1,255
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.
Author by
Joel Broström
Updated on December 30, 2022Comments
-
Joel Broström over 1 year
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?
-
Simon Sot almost 3 years
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. -
pskink almost 3 yearsread carefully A tour of the Dart language - section about
Functions
-
-
Joel Broström almost 3 yearsIt 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.