Return Values
Functions in Dart can return values back to the code that called them. Think of it like asking a friend a question - they process your question and give you an answer back. That "answer" is the return value!
What are Return Values?
A return value is the result that a function sends back after it finishes executing. When you call a function, you might want to get some information or a calculated result from it.
Basic Return Syntax
To return a value from a function, use the return keyword followed by the value you want to send back:
// Function that returns a string
String greetUser(String name) {
return "Hello, $name!";
}
// Function that returns a number
int addNumbers(int a, int b) {
return a + b;
}
Using Return Values
When a function returns a value, you can capture it in a variable or use it directly:
// Capturing return value in a variable
String greeting = greetUser("Alice");
print(greeting); // Output: Hello, Alice!
// Using return value directly
print(addNumbers(5, 3)); // Output: 8
// Using return value in calculations
int result = addNumbers(10, 20) * 2;
print(result); // Output: 60
Return Types
The return type tells Dart what kind of value the function will return. Here are some common return types:
| Return Type | Description | Example |
|---|---|---|
int | Returns an integer | int getAge() { return 25; } |
String | Returns a string | String getName() { return "John"; } |
bool | Returns true or false | bool isAdult(int age) { return age >= 18; } |
double | Returns a decimal number | double getPrice() { return 19.99; } |
Multiple Return Statements
A function can have multiple return statements, but only one will execute:
String checkGrade(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
Void Functions
Some functions don't return anything - they just perform actions. These use the void return type:
void printWelcome() {
print("Welcome to our app!");
// No return statement needed
}
Early Returns
You can use return statements to exit a function early:
String validatePassword(String password) {
if (password.length < 8) {
return "Password too short";
}
if (!password.contains(RegExp(r'[0-9]'))) {
return "Password must contain a number";
}
return "Password is valid";
}
Best Practices
- Always specify the return type of your functions
- Make sure all code paths return a value (except for void functions)
- Keep return statements simple and clear
- Use meaningful return values that make sense in context
Return values make functions incredibly powerful because they allow functions to communicate results back to the rest of your program, enabling you to build complex logic by combining simple functions together!