Dart Function Types
In Dart, named functions are functions that are defined with a specific name and can be called multiple times in a program. Named functions can have parameters, return values, and can be defined at different levels within the program (globally, inside classes, or inside other functions).
Here’s a breakdown of how to work with named functions in Dart, including defining functions with parameters, using optional parameters, and specifying default values.
1. Basic Named Function
A basic named function in Dart is declared using the void
keyword if it doesn’t return a value or by specifying a return type like int
, String
, etc.
Output:
2. Function with Parameters
You can define a function with parameters so that it can accept input values.
Output:
3. Function with Return Value
If a function needs to return a value, specify the return type instead of void
, and use the return
keyword to send a value back.
Output:
4. Optional Positional Parameters
You can make parameters optional by placing them inside square brackets []
. If not provided, optional parameters have a null
value by default.
Output:
5. Named Parameters
Dart also supports named parameters, which are defined inside curly braces {}
. Named parameters make the code more readable, as you specify the parameter name when calling the function.
Output:
6. Default Values for Named Parameters
You can set default values for named parameters to ensure they have a specific value if not explicitly provided.
Output:
7. Anonymous Functions with Named Function Assignment
Dart allows you to define anonymous functions and assign them to variables. These can be passed as parameters or stored for later use.
Output:
Summary
- Basic named functions: Defined with a name, can take parameters, and can return values.
- Optional parameters: Defined within
[]
, are optional and default tonull
. - Named parameters: Defined with
{}
, require explicit names when calling. - Default values: Provide default values for parameters within the function definition.
Dart’s function flexibility helps make code concise and readable, offering control over function parameters and behavior in various scenarios.