函数定义
Function 类
- 函数也是对象.
bool isNoble(int atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
// 函数签名可以忽略返回值
isNoble(atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
函数体只有一行可以简写:
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;
参数
可选参数
可选参数可以是 named 或者 positional, 但不能都是.
Named 参数
{}
// 定义
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}
// 调用
// 也就是说 named 参数在传递时可以时随意位置
enableFlags(bold: true, hidden: false);
- 强制某个参数必须赋值
// 使用 required 注解依赖 meta 包
import package:meta/meta.dart
const Scrollbar({Key key, @required Widget child})
Positional 参数
[]
// 定义
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
// 调用
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
// 也就是说 positional 参数在传递时必须按照顺序
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');
默认参数值
- 参数值必须是编译时常量
为 named 参数指定默认值:
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}
// bold will be true; hidden will be false.
enableFlags(bold: true);
为 positional 参数指定默认值:
String say(String from, String msg,
[String device = 'carrier pigeon', String mood]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
if (mood != null) {
result = '$result (in a $mood mood)';
}
return result;
}
assert(say('Bob', 'Howdy') ==
'Bob says Howdy with a carrier pigeon');
参数使用 list 或 map 默认值:
void doStuff(
{List<int> list = const [1, 2, 3],
Map<String, String> gifts = const {
'first': 'paper',
'second': 'cotton',
'third': 'leather'
}}) {
print('list: $list');
print('gifts: $gifts');
}
main() 函数
- main() 函数必须有
..
被称为 cascade (级联)
void main() {
querySelector('#sample_text_id')
..text = 'Click me!'
..onClick.listen(reverseText);
}
- main() 函数可以有参数, 用于接收命令行参数
// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
print(arguments);
assert(arguments.length == 2);
assert(int.parse(arguments[0]) == 1);
assert(arguments[1] == 'test');
}
函数是一等对象
- 函数可以作为参数传递给其它函数
void printElement(int element) {
print(element);
}
var list = [1, 2, 3];
// Pass printElement as a parameter.
list.forEach(printElement);
- 给变量分配函数值
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
assert(loudify('hello') == '!!! HELLO !!!');
匿名函数
- 定义匿名函数时, type 可以不写
// 语法
([[Type] param1[, …]]) {
codeBlock;
};
var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});
词法范围
变量的范围是静态确定的.
bool topLevel = true;
void main() {
var insideMain = true;
void myFunction() {
var insideFunction = true;
void nestedFunction() {
var insideNestedFunction = true;
assert(topLevel);
assert(insideMain);
assert(insideFunction);
assert(insideNestedFunction);
}
}
}
词法闭包
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
void main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
测试函数是否相等
void foo() {} // A top-level function
class A {
static void bar() {} // A static method
void baz() {} // An instance method
}
void main() {
var x;
// Comparing top-level functions.
x = foo;
assert(foo == x);
// Comparing static methods.
x = A.bar;
assert(A.bar == x);
// Comparing instance methods.
var v = A(); // Instance #1 of A
var w = A(); // Instance #2 of A
var y = w;
x = w.baz;
// These closures refer to the same instance (#2),
// so they're equal.
assert(y.baz == x);
// These closures refer to different instances,
// so they're unequal.
assert(v.baz != w.baz);
}
返回值
所有函数都有返回值, 如果在代码中没写 return, 那么 dart 自动在函数体最后加上 return null;
.
foo() {}
assert(foo() == null);