Functions
Functions are reusable blocks of code that perform specific tasks. In Dart, functions are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
Basic Function Syntax
Parameters
Required Positional Parameters
Optional Positional Parameters
Use square brackets []:
Named Parameters
Use curly braces {}:
Required Named Parameters
Default Parameter Values
Return Values
Anonymous Functions (Lambdas)
Higher-Order Functions
Functions that take other functions as parameters or return functions:
Closures
Functions that capture variables from their surrounding scope:
Recursive Functions
Generator Functions
Synchronous Generator
Returns an Iterable:
Asynchronous Generator
Returns a Stream:
Function Types
Best Practices
- Use arrow syntax for simple one-line functions
- Prefer named parameters for functions with multiple parameters
- Use required for mandatory named parameters
- Keep functions small and focused on a single task
- Use descriptive names that indicate what the function does
- Document complex functions with comments