Skip to content
Related Articles

Related Articles

Dart – Getters and Setters

Improve Article
Save Article
Like Article
  • Last Updated : 14 Jul, 2020

Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. 

  • Getters or accessors are defined using the get keyword.
  • Setters or mutators are defined using the set keyword.

A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value.

Syntax: Defining a getter
Return_type  get identifier  
    // statements
Syntax: Defining a setter
set identifier  
   // statements

Example 1:

The following example shows how you can use getters and setters in a Dart class:


// Dart Program in Dart to illustrate
// getters and setters #GFG
class Student { 
   String name; 
   int age; 
   String get stud_name { 
      return name; 
   void set stud_name(String name) { = name; 
   void set stud_age(int age) { 
      if(age<= 0) { 
        print("Age should be greater than 5"); 
         this.age = age; 
   int get stud_age { 
      return age;     
void main() { 
   Student s1 = new Student(); 
   s1.stud_name = 'Nitin'
   s1.stud_age = 0; 


Age should be greater than 5  

Example 2:


// Dart program in Dart to illustrate
// getters and setters #GFG
void main() {
  var cat = new Cat();
  // Is cat hungry? true
  print("Is cat hungry? ${cat.isHungry}");
  // Is cat cuddly? false
  print("Is cat cuddly? ${cat.isCuddly}");  
  print("Feed cat.");
  cat.isHungry = false;   
  // Is cat hungry? false
  print("Is cat hungry? ${cat.isHungry}");
   // Is cat cuddly? true
  print("Is cat cuddly? ${cat.isCuddly}"); 
class Cat {
  bool _isHungry = true;
  bool get isCuddly => !_isHungry;
  bool get isHungry => _isHungry;
  bool set isHungry(bool hungry) => this._isHungry = hungry;


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!