20

I am new to Dart and Flutter, I wanted to know what i the actual difference and when to use which one.

1 Answer 1

31

A function is a top-level function which is declared outside of a class or an inline function that is created inside another function or inside method.

A method is tied to an instance of a class and has an implicit reference to 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`
  void 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  
  }
}

Like inline functions you can also create unnamed inline functions, also called closures. They are often used as callbacks like

button.onClick.listen( /* function start */ (event) {
  print(event.name);
  handleClick();
} /* function end */);
4
  • 5
    Static ("class") methods are not tied to an instance of the class and have no access to "this". Commented Dec 6, 2018 at 2:24
  • 2
    A bit late, but method for statics is a bit of a misnomer anyway, they are functions with the class name as additional namespace. Commented Mar 7, 2019 at 4:55
  • 1
    If I pass a function to be a class field, does that field becomes a method? For example, I pass a callback function to a widget, and that function is stored in a class field, which can be called in the same way as a method defined in a class. Does that callback function becomes a method of the object? Commented Apr 3 at 11:08
  • @MichaelTsang no, it is only a method when it's defined as part of a class. If it's defined somewhere else and passed to a class it's still just a reference to the original function. Commented Apr 7 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.