Getter and Setter Methods in Dart

Getter and setter methods are the class methods used to manipulate the data of the class fields. Getter is used to read or get the data of the class field whereas setter is used to set the data of the class field to some variable.

Getter Method in Dart

It is used to retrieve a particular class field and save it in a variable. All classes have a default getter method but it can be overridden explicitly. The getter method can be defined using the get keyword as:

return_type get field_name{
    ...
}

It must be noted we have to define a return type but there is no need to define parameters in the above method.

Setter Method in Dart

It is used to set the data inside a variable received from the getter method. All classes have a default setter method but it can be overridden explicitly. The setter method can be defined using the set keyword as:

set field_name{
    ...
}

Example: Using the Getter and Setter method in the dart program.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// Creating Class named Gfg 
class Gfg {
    
  // Creating a field
  String geekName;
    
  // Using the getter
  // method to take input
  String get geek_name {
    return geekName;
  }
    
  // Using the setter method
  // to set the input
  set geek_name (String name) {
    this.geekName = name;
  }
  
void main() 
    // Creating Instance of class 
    Gfg geek = new Gfg(); 
    
  // Calling the geek_name
  // getter method to get the name
    geek.geek_name = "GeeksForGeeks";
    
  // Printing the input 
  // taken through getter method
  print("Welcome to ${geek.geek_name}");
}

chevron_right


Output:

Welcome to GeeksForGeeks
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 :

1


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