Skip to main content

'get' & 'set' as getters and setters

get and set are 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

get is called just like a variable as obj.get_VariableName

get getterint function()
don't need parameters as its called like a variablecan take parameters
=> is used=> is used as its a function with a return type
called by obj.get_VariableNamecalled 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, get also 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

  • get means method of return type
  • set means 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];
}