thumbnail

Getters And Setters in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Every instance variable in Dart has an implicit getter and a setter. By defining a custom getter and setter in Dart you can override the default getter and setter.

Various operators such as -- work as intended with getters and setters in Dart. Dart uses various heuristics to make this possible.

Getters and setters are also known as accesssors and mutators in Dart.

Number of parameters for getters and setters

  • A getter has no parameters.
  • A setter has exactly one parameter. A setter does not allow defining more than one parameter.

Syntax for defining getters and setters in Dart

Given below is the general syntax for getters and setters in Dart.

Syntax for setters:

set identifier(type variable_name){
   // statements
}

Syntax for getters:

return_type get identifier{
   // statements
}

Refer to the program given below that will help you to understand how to use above syntax.

Program to demonstrate use of Getters and Setters in Dart

// program to demonstrate use of getters and setters in dart

class Person {
  // name of the person
  String _name;

  Person(this._name);

  // getter
  String get name {
    return _name;
  }

  // setter
  void set name(newName) {
    _name = newName;
  }

  void printName() {
    print('Name of the person is: ${name}');
  }
}

main(List<String> args) {
  // creating new instance of Person object
  var p = new Person('john');
  p.printName();

  // using setter
  p.name = 'robert';
  p.printName();

  // using getter to get the name
  print('Name of the person is: ${p.name}');
}

Above program produces following output:

Name of the person is: john
Name of the person is: robert
Name of the person is: robert