Open In App

Getter and Setter Methods in Dart

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Getter and Setter methods are class methods used to manipulate the data of 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.

getterandsetter


The following diagram illustrates a Person class that includes:

  • A private variable _name, which can only be accessed within the class.
  • A getter method, getName() that retrieves the value of _name.
  • A setter method setName() that enables controlled modification of _name.

This visual representation aids in understanding encapsulation in Dart, ensuring that direct access to _name is restricted while still allowing for controlled read and write operations.

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 that 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{
...
}


Getter and Setter Methods in the dart program

Example :

Dart
// Creating Class named Gfg
class Gfg {
    
    // Creating a Field/Property
    String geekName = '';
    
    // Creating the getter method to
    // get input from Field/Property
    String get getName {
        return geekName;
    }
    
    // Creating the setter method to
    // set the input in Field/Property
    set setName(String name) {
        geekName = name;
    }
}

void main() {
    
    // Creating Instance of class
    Gfg geek = Gfg();
    
    // Calling the set_name method(setter method we created)
    // To set the value in Property "geekName"
    geek.setName = "GeeksForGeeks";
    
    // Calling the get_name method(getter method we created)
    // To get the value from Property "geekName"
    print("Welcome to ${geek.getName}");
}


Output:

Welcome to GeeksForGeeks

Conclusion

Getter and setter methods are essential for encapsulation and data management in Dart. They provide controlled access to class fields, ensuring that any modifications to the data follow established constraints. By using these methods, developers can create cleaner, more maintainable, and more secure code.


Next Article
Article Tags :

Similar Reads