The ‘null’ return issue in Dart
In Dart, when a function or method has a non-nullable return type (denoted by adding a ‘?’ after the type), it is required to either have a return statement or throw an exception at the end of the function body. If the function body completes normally without a return statement, Dart will implicitly return ‘null’ for non-nullable types, leading to a compile-time error.
Let’s see an example to understand this better:
void myFunction() {
// Function body
// Missing return or throw statement
}
void main() {
myFunction();
}
In the above code, the function myFunction()
does not have a return or throw statement at the end. Since it has a non-nullable return type, Dart will implicitly return ‘null’ causing a compile-time error. This error can be fixed by adding either a return statement or throw statement at the end of the function body.
Here’s an updated example with a return statement:
String myFunction() {
// Function body
return "Hello World";
}
void main() {
String result = myFunction();
print(result);
}
In the updated code, the function myFunction()
now has a return statement at the end. It returns a string “Hello World”. In the main()
function, the returned value is stored in the variable result
and printed to the console.