Dart Functions
A function is the basic unit for organizing code; it encapsulates a piece of reusable logic that can be called when needed.
Dart's function system is very flexible, supporting named parameters, optional parameters, arrow functions, and higher-order functions.
Function definition and return values
A function consists of a return type, a function name, a parameter list, and a function body.
Example
// Define a simple function
// String is the return type, greet is the function name, (String name) is the parameter list
String greet
(
String name
)
{
return
'Hello, $name! Welcome to RUNOOB.'
;
}
// Functions with no return value use void
void
printWelcome
(
)
{
(
'=== RUNOOB Dart Tutorial ==='
)
;
}
void
main
(
)
{
printWelcome
(
)
;
// Call the function and receive its return value
String message
=
greet
(
'Xiao Ming'
)
;
(
message
)
;
}
=== RUNOOB Dart 教程 ===
你好,小明!欢迎来到 RUNOOB。
Return Value
Every function has a return value.
If there is no explicit return, the function implicitly returns null (but under null safety this causes a type mismatch, so void is usually used to indicate no return value).
Example
// A function that returns an int
int
add
(
int
a
,
int
b
)
{
return
a
b
;
}
// Use arrow syntax for shorthand single-expression functions
int
multiply
(
int
a
,
int
b
)
=>
a
b
;
// void means there is no meaningful return value
void
log
(
String msg
)
{
(
'[RUNOOB log] $msg'
)
;
}
void
main
(
)
{
(
'3 + 5 = ${add(3, 5)}'
)
;
(
'3 × 5 = ${multiply(3, 5)}'
)
;
log
(
'Function learning complete'
)
;
}
3 + 5 = 8
3 × 5 = 15
[RUNOOB 日志] 函数学习完成
Named parameters and optional parameters
Dart parameters come in two kinds: required parameters (required) and optional parameters.
Optional parameters are further divided into named parameters (named) and positional parameters (positional).
Named Parameters
Named parameters are wrapped in curly braces {} and passed by parameter name when called, in any order.
Example
// Curly braces {} contain named parameters, which are optional by default
// The required keyword marks a parameter as mandatory
String createUser
(
{
required String name
,
// Required named parameters
int
age
=
0
,
// Optional, default value is 0
String
?
,
// Optional, can be null
bool
isVip
=
false
,
// Optional, default value is false
}
)
{
var
info
=
'Username: $name, age: $age'
;
if
(
!=
null
)
{
info
=
', email: $email'
;
}
if
(
isVip
)
{
info
=
' [VIP user]'
;
}
return
info
;
}
void
main
(
)
{
// Named parameters: passed by parameter name, order-independent
(
createUser
(
name
:
'runoob'
,
age
:
10
)
)
;
(
createUser
(
name
:
'admin'
,
:
'admin@runoob.com'
,
isVip
:
true
)
)
;
// Required parameters cannot be omitted
// createUser(); // Error: missing required parameter name
}
用户名: runoob, 年龄: 10
用户名: admin, 邮箱: admin@runoob.com [VIP用户]
Positional Parameters
Positional parameters are wrapped in square brackets [] and passed in order when called.
Example
// Square brackets [] contain optional positional parameters
String buildUrl
(
String host
,
[
String path
=
'/'
,
int
port
=
80
]
)
{
return
'http://$host:$port$path'
;
}
void
main
(
)
{
// Pass only required parameters; optional parameters use default values
(
buildUrl
(
'www.runoob.com'
)
)
;
// Pass 2 parameters
(
buildUrl
(
'www.runoob.com'
,
'/dart'
)
)
;
// Pass 3 parameters
(
buildUrl
(
'localhost'
,
'/api'
,
8080
)
)
;
}
http://www.runoob.com:80/
http://www.runoob.com:80/dart
http://localhost:8080/api
Named parameters vs positional parameters: how to choose
| Scenario | Recommended approach | Reason |
|---|---|---|
| Many parameters (more than 3) | named parameters | Parameter names are self-documenting at call sites, less prone to wrong order |
| Parameter meaning is not obvious | named parameters | Values like true/false do not convey purpose; adding a name is clearer |
| Few parameters with clear meaning | positional parameters | Such as add(1, 2), concise and clear |
| Flutter Widget construction | named parameters | Flutter standard style |
A function cannot use both optional positional parameters and optional named parameters at the same time. You can only choose one.
Default parameter values
Optional parameters can specify default values, which are used when the caller does not pass the parameter.
Example
// All optional parameters have default values
String formatMessage
(
String content
,
{
String prefix
=
'[RUNOOB]'
,
String suffix
=
''
,
bool
uppercase
=
false
,
}
)
{
var
result
=
'$prefix $content $suffix'
;
return
uppercase
?
result.
toUpperCase
(
)
:
result
;
}
void
main
(
)
{
// Use all default values
(
formatMessage
(
'Dart Tutorial updated'
)
)
;
// Override some default values
(
formatMessage
(
'Important notice'
,
prefix
:
'[Announcement]'
,
suffix
:
'!!!'
)
)
;
// Override default values + enable uppercase
(
formatMessage
(
'error'
,
prefix
:
'[Error]'
,
uppercase
:
true
)
)
;
}
[RUNOOB] Dart 教程更新了
[公告] 重要通知 !!!
[错误] ERROR
Default values must be compile-time constants. That is, a default value cannot be DateTime.now() or the return value of some function (unless that function is const). If the default needs to be determined at runtime, you can handle it inside the function body with ??.
Arrow functions and anonymous functions
When the function body has only a single expression, you can use the arrow syntax (=>) as shorthand.
An anonymous function is a function without a name, usually passed as an argument to other functions.
Example
void
main
(
)
{
var
numbers
=
[
1
,
2
,
3
,
4
,
5
]
;
// Anonymous function (full form)
numbers.
forEach
(
(
number
)
{
(
'RUNOOB number: $number'
)
;
}
)
;
(
'---'
)
;
// Arrow function (single-expression shorthand)
var
doubled
=
numbers.
map
(
(
n
)
=>
n
2
)
;
(
'Doubled: $doubled'
)
;
// Using arrow functions in function definitions
// When the function body has only a single return statement, you can use the => shorthand
int
square
(
int
x
)
=>
x
x
;
(
'5 squared: ${square(5)}'
)
;
// Store an anonymous function in a variable
var
sayHello
=
(
String name
)
=>
'Hello, $name!'
;
(
sayHello
(
'runoob'
)
)
;
}
RUNOOB 数字: 1
RUNOOB 数字: 2
RUNOOB 数字: 3
RUNOOB 数字: 4
RUNOOB 数字: 5
---
翻倍: (2, 4, 6, 8, 10)
5 的平方: 25
你好,runoob!
Higher-Order Functions and Closures
A higher-order function is a function that can take a function as a parameter, or return a function as its result.
A closure is a function that can access variables in its lexical scope, even when the function is called outside that scope.
Higher-Order Functions
Example
// Higher-order function: takes a function as a parameter
List
<
int
filterList
(
List
<
int
items
,
bool
Function
(
int
)
predicate
)
{
returnitems.
where
(
predicate
)
.
toList
(
)
;
}
// Higher-order function: returns a function
Function makeMultiplier
(
int
factor
)
{
// Returns a closure: it remembers the outer factor
return
(
int
n
)
=>
n
factor
;
}
void
main
(
)
{
var
numbers
=
[
10
,
15
,
20
,
25
,
30
]
;
// Pass in an anonymous function as the filter condition
var
bigNumbers
=
filterList
(
numbers
,
(
n
)
=>
n
18
)
;
(
'RUNOOB numbers greater than 18: $bigNumbers'
)
;
// Get the returned function
var
doubleIt
=
makeMultiplier
(
2
)
;
var
tripleIt
=
makeMultiplier
(
3
)
;
(
'5 × 2 = ${doubleIt(5)}'
)
;
(
'5 × 3 = ${tripleIt(5)}'
)
;
}
RUNOOB 大于18的数: [20, 25, 30]
5 × 2 = 10
5 × 3 = 15
Closures
A closure is a function object that can access variables in its lexical scope, even when the function is called outside its original scope.
Example
// A classic use of closures: creating a counter
Function makeCounter
(
)
{
int
count
=
0
;
// This variable is "captured" by the returned function
return
(
)
{
count
++
;
return
count
;
}
;
}
void
main
(
)
{
// counterA and counterB each have their own independent count
var
counterA
=
makeCounter
(
)
;
var
counterB
=
makeCounter
(
)
;
(
'RUNOOB Counter A: ${counterA()}'
)
;
// 1
(
'RUNOOB Counter A: ${counterA()}'
)
;
// 2
(
'RUNOOB Counter B: ${counterB()}'
)
;
// 1 (independent count)
(
'RUNOOB Counter A: ${counterA()}'
)
;
// 3
}
RUNOOB 计数器 A: 1
RUNOOB 计数器 A: 2
RUNOOB 计数器 B: 1
RUNOOB 计数器 A: 3
The key to closures is that the inner function "remembers" the variables of the outer function even after the outer function has finished executing. Each call to makeCounter() creates a brand-new count variable and closure, so multiple counters do not affect each other.