Dart Returning Values
A returning function sends a value back to the place that called it. The word return hands that value back.
A value sent back
doubleIt takes one number and return hands back twice that number. print shows the value that came back.
int doubleIt(int n) {
return n * 2;
}
void main() {
print(doubleIt(4));
}Storing the value that comes back
The value from add goes into total. The prints show total and then total plus 1.
int add(int a, int b) {
return a + b;
}
void main() {
var total = add(3, 5);
print(total);
print(total + 1);
}An early return
A score of 50 or more hits the first return and the body ends there. A lower score falls past the if and hits the second return.
String grade(int score) {
if (score >= 50) {
return 'pass';
}
return 'fail';
}
void main() {
print(grade(70));
print(grade(30));
}A function that never sends a value back
The body of score holds a variable and no return line. The compiler stops and asks for a value.
int score() {
var points = 10;
}
void main() {
print(score());
}Example
int priceWithTax(int price) {
return price + 2;
}
void main() {
var total = priceWithTax(10);
print(total);
print(priceWithTax(20));
}Key points
- Use return to send a value back from a function.
- The kind before the function name says what kind of value comes back.
- A caller can store the value that comes back in a variable.
- A caller can use the value that comes back inside print.
- A return ends the function at once.
- Lines after a return in the same path do not run.
In this example, priceWithTax adds 2 to its price and return sends that sum back. The first call passes 10 and the sum 12 goes into total. The first print shows 12. The second call passes 20 inside print, and the print shows 22.
Note
Every path through a function with a value kind must reach a return, or the code does not compile.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does return do in a function?