我是Dart和Flutter的新手,我想知道我的实际区别以及何时使用哪一个。
答案 0 :(得分:5)
一个函数是一个顶层函数,它是在类外部或在另一个函数或方法内部创建的内联函数中声明的。
方法绑定到类的实例,并具有对this
的隐式引用。
main.dart
// 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
}
}
类似于内联函数,您还可以创建未命名的内联函数,也称为闭包。它们通常用作回调,例如
button.onClick.listen( /* function start */ (event) {
print(event.name);
handleClick();
} /* function end */);