Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Function and Method in Dart programming language?

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

like image 236
sameer shaik Avatar asked Nov 30 '18 17:11

sameer shaik


People also ask

What is difference between function and method?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.

What is a method in Dart?

Dart Masterclass Programming: iOS/Android Bible A method is a combination of statements which is used to attach some behavior to the class objects. It is used to perform some action on class objects, and we name methods so that we can recall them later in the program.

What is function in Dart Flutter?

A function (also might be referenced to as method in the context of an object) is a subset of an algorithm that is logically separated and reusable. It can return nothing (void) or return either a built-in data type or a custom data type. It can also have no parameters or any number of parameters.

How many functions are there in Dart?

Basically, there are four types of functions in Dart.


1 Answers

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 */);
like image 195
Günter Zöchbauer Avatar answered Sep 28 '22 09:09

Günter Zöchbauer