Functions — Syntax & Return Types
Functions: Syntax and Return Types
A function is a reusable block of code designed to perform a specific task. Functions prevent code duplication, help organize code into logical modules, and make programs easier to test.
Dart is a true object-oriented language, meaning functions are objects and have a type (Function). This allows functions to be assigned to variables or passed as arguments.
Basic Function Syntax
A standard Dart function consists of a return type, a descriptive name, a parameter list enclosed in parentheses, and a body enclosed in curly braces.
dartReturnType functionName(ParameterType parameter1, ParameterType parameter2) { // Function body return value; }
If you do not specify a return type, Dart defaults to dynamic, but you should always explicitly annotate return types for clean code.
dart// Example function returning an integer int add(int a, int b) { return a + b; } // Example function returning nothing (void) void greet(String name) { print("Hello, $name!"); } void main() { int result = add(5, 3); print(result); // 8 greet("Alice"); // Hello, Alice! }
Return Types in Dart
Functions can return any valid type in Dart.
void: Indicates that the function does not return a value. If a function reaches the end of its body without a return statement, it implicitly returnsnull.- Primitive Types:
int,double,String,bool. - Collections:
List,Set,Map. - Objects: Custom class instances.
Never: Indicates that the function never returns (e.g., it always throws an exception).
dartList<String> getRoles() { return ["Admin", "User", "Guest"]; }
Single-Expression Functions (Arrow Syntax)
For functions that contain only a single expression (a single line of code that evaluates to a value), Dart provides a shorthand arrow syntax (=>).
dart// Standard syntax int square(int number) { return number * number; } // Arrow syntax equivalent int squareArrow(int number) => number * number;
[!NOTE]
Only an expression, not a statement, can appear between the arrow (=>) and the semicolon. You cannot write a block with curly braces or use a return keyword with arrow syntax.
Summary
- Functions group reusable code blocks.
- Explicitly declare the return type and parameter types to catch errors early.
- Use
voidif the function does not return a value. - Use the arrow syntax (
=>) shorthand for simple, single-expression functions.