Functions
Dart Functions#
Functions in Dart are reusable blocks of code that can be called with or without parameters. They help to reduce redundancy and make the code more modular and easier to understand. Functions can return values, and you can also create functions without return values (void functions).
How Functions Work#
- Definition: A function is defined using the
returnType
followed by the function name and parameters. - Return Type: This specifies the type of value the function will return (e.g.,
int
,String
,bool
). If the function doesn’t return a value, usevoid
. - Parameters: Functions can take parameters that you can pass values to when you call them.
- Body: The body of the function is enclosed in curly braces
{}
and contains the logic to execute.
How to Use#
- Define the Function: Specify the return type, name, and any parameters.
- Call the Function: Invoke the function from anywhere in your program by using its name and providing arguments, if required.
- Use the Returned Value (if applicable): If the function returns a value, you can store or use it immediately.
Example#
// Function with return type
int addNumbers(int a, int b) {
return a + b;
}
// Void function (no return type)
void printGreeting(String name) {
print('Hello, $name!');
}
void main() {
// Calling the function with a return value
int result = addNumbers(5, 3);
print('The result is: $result');
// Calling the void function
printGreeting('Alice');
}
Notes:#
Functions help in breaking down code into smaller, reusable pieces. Use functions when a particular task is repetitive or when the code can be logically separated.