Skip to main content
A function in Dart is a first-class object of type Function that encapsulates a reusable block of code. Because Dart is a true object-oriented language, functions can be assigned to variables, passed as arguments to other functions, and returned as results from other functions.

Basic Syntax

A standard function declaration includes a return type, an identifier, a parameter list, and a block body. Type annotations are optional but recommended for static type checking.
If no return type is explicitly defined, it defaults to dynamic. If a function does not explicitly return a value, it implicitly returns null.

Parameter Structures

Dart categorizes parameters into two primary types: positional and named. A function can utilize both, but positional parameters must precede named parameters.

1. Positional Parameters

Arguments are mapped to parameters based on their exact position in the signature.
  • Required Positional: Must be provided by the caller.
  • Optional Positional: Wrapped in square brackets []. They must be nullable or have a default value.

2. Named Parameters

Arguments are passed by name, making the call site order-independent. They are wrapped in curly braces {}. Named parameters are optional by default unless explicitly annotated with the required keyword.

Arrow Syntax (Expression Bodies)

For functions containing only a single expression, Dart provides the => (fat arrow) shorthand. The => expr syntax is strictly equivalent to { return expr; }. It accepts only an expression, not a statement.

Anonymous Functions

Functions can be declared without an identifier. These are known as anonymous functions, lambdas, or closures. They consist of a parameter list followed by a block body or an arrow expression.

Lexical Scope and Closures

Dart is a lexically scoped language, meaning the scope of variables is determined statically by the layout of the code. A closure is a function object that captures variables from its lexical scope. The function retains access to those variables even if it is executed outside of their original scope.

Generator Functions

Dart supports generator functions to lazily produce a sequence of values.
  • Synchronous Generator: Returns an Iterable. Marked with sync* and yields values using the yield keyword.
  • Asynchronous Generator: Returns a Stream. Marked with async* and yields values asynchronously.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More