函数是在类之外声明的顶级函数,或者是在另一个函数或方法内部创建的内联函数。
方法绑定到类的实例,并隐式引用this。
主镖
// function
void foo() => print('foo');
// function
String bar() {
return 'bar';
}
void fooBar() {
int add(int a, int b) => a + b; // inline function
int value = 0;
for(var i = 0; i < 9; i++) {
value = add(value, i); // call of inline function
print(value);
}
}
class SomeClass {
static void foo() => print('foo'); // function in class context sometimes called static method but actually not a method
SomeClass(this.firstName);
String firstName;
// a real method with implicit access to `this`
String bar() {
print('${this.firstName} bar');
print('$firstName bar'); // this can and should be omitted in Dart
void doSomething() => print('doSomething'); // inline function declared in a method
doSomething(); // call of inline function
}
}
Run Code Online (Sandbox Code Playgroud)
像内联函数一样,您也可以创建未命名的内联函数,也称为闭包。它们经常用作回调,例如
button.onClick.listen( /* function start */ (event) {
print(event.name);
handleClick();
} /* function end */);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1357 次 |
| 最近记录: |