'get' & 'set' as getters and setters
getandsetare just syntactic sugar and are just type of methods. So, everything they do can also be done by simple user-define methods/functions.
get - getters
int get val => returnValue; .. MUST have return type
Purpose: to get or access a value may be to print or assign to other variables or use anywhere else.
Example of default getter is: print(obj.x);
get is a short form of writing a function of return type
getis called just like a variable asobj.get_VariableName
get getter | int function() | |
|---|---|---|
| don't need parameters as its called like a variable | can take parameters | |
=> is used | => is used as its a function with a return type | |
called by obj.get_VariableName | called by obj.functionName() parenthesis() is used as functionName is a function |
info
int get area => width * height;
/* called as: */
// print(obj.area);
'get' without '=>'
int get area {
return width * height;
}
'get'⏫ is shortform of:
int area() {
return width * height;
}
/* called as: */
// print(obj.area());
So,
getalso known as getters are syntactic-sugar for user-defined methods which created using=>.
set - setters
set increment(CounterModel obj) => ++obj.x; .. MUST NOT have any type
getmeans method of return typesetmeans method of void type with a single parameter
import 'package:equatable/equatable.dart';
class CounterModel extends Equatable {
final int x = 0;
void set increment(x) => ++x;
void set decrement(x) => --x;
@override
List<Object?> get props => [x];
}