Dart编程语言中的Function和Method有什么区别?

sam*_*aik 1 methods function dart flutter

我是Dart和Flutter的新手,我想知道我的实际区别是什么以及何时使用哪一个。

Gün*_*uer 8

函数是在类之外声明的顶级函数,或者是在另一个函数或方法内部创建的内联函数。

方法绑定到类的实例,并隐式引用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)

  • 静态(“类”)方法不绑定到类的实例并且无法访问“this”。 (3认同)