Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Setters and Getters allow you to read and update the data of a class object. It uses to achieve encapsulation

Dart setter and getter examples

In classes, Getters provide an access to read instance member variables. Setters allow you to update the instance variables of a class.

Getters are called accessors, and Setters are known as Mutators.

In Dart, Getter and Setters are implicitly defined for every member declared in a class Still, You can customize the fields to write setters and getters

Getter’s syntax:

datatype get member_name{
// code to return members
}

Setters Syntax:

set  member_name{
// code to update members
}

Here is an example code

  • First, Declare fields or member variables in a class with the type
  • provide setter and Getter methods with set and get keyword
  • Can access getter using an instance of a class assign the value to class field instance.field=value.
  • Getter can be accessed using instance.field.

Here is an example program

class Employee {
  int _eid;
  String _name;

  int get id {
    return _eid;
  }

  set id(int eid) {
    _eid = eid;
  }

  String get name {
    return _name;
  }

  set name(String name) {
    _name = name;
  }
}

void main() {
  Employee emp = Employee();
  emp.id = 12;
  emp.name = "john";

  print("${emp.id} - ${emp.name}");
}

Output:

12 - john

Similarly, You can rewrite the getter methods with shorter syntax. arrow(=>) function to replace an existing function with a shorter syntax expression.

  int get id => _eid;

Here is an example program

class Employee {
  int _eid;
  String _name;

  int get id => _eid;

  set id(int eid) {
    _eid = eid;
  }

  String get name => _name;

  set name(String name) {
    _name = name;
  }
}

void main() {
  Employee emp = Employee();
  emp.id = 12;
  emp.name = "john";

  print("${emp.id} - ${emp.name}");
}

Similarly, can use setters and getters for private members in the library.