Dart – Getters and Setters

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



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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) { 
      this.name = name; 
   
     
   void set stud_age(int age) { 
      if(age<= 0) { 
        print("Age should be greater than 5"); 
      else
         this.age = age; 
      
   
     
   int get stud_age { 
      return age;     
   
}  
void main() { 
   Student s1 = new Student(); 
   s1.stud_name = 'Nitin'
   s1.stud_age = 0; 
   print(s1.stud_name); 
   print(s1.stud_age); 
}

chevron_right


Output:

Age should be greater than 5  
Nitin
Null 

Example 2:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:




My Personal Notes arrow_drop_up

Stepping steps of my ownself

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.