I am new to Dart and Flutter, I wanted to know what i the actual difference and when to use which one.
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.
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.
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.
Basically, there are four types of functions in Dart.
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 */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With