Appearance
函数
函数定义
dart
// 函数定义
void sayHello(){
print('hello');
}参数
函数有必需参数和可选参数。可选参数可以是命名参数或位置参数。
dart
// 位置参数
void sayHello(String name){
print('hello $name');
}
// 可选参数。命名参数必须在位置参数之后。
// 方括号意味着可选
void sayHello2({String name = '张三'},[int age = 20]){
print('hello $name, you are $age years old');
}[]:可选位置参数 → 靠顺序匹配,调用时直接写值(如 printMessage("Hi", "Tip")); {}:可选命名参数 → 靠参数名匹配,调用时要写 参数名: 值(如 printInfo(name: "Alice"))
函数的特殊使用
- 作为参数
dart
int multiAdd(Function func, int times){
int result = 0;
for(int i = 0;i<times;i++){
result += func(i);
}
return result;
}- 作为返回值dart
// 作为返回值 Function add(int a, int b) { return (int c) => a + b + c; }