Dart : Getter & Setter

Dart : Getter & Setter

·

2 min read

What are the getter and setter methods in Dart?

  • The class methods , getter and setter , are used to manipulate the data of the
    class attributes.

  • A setter is used to set the data of the fieldName class to same variable , whereas
    a getter is used to read or get the data of the fieldName class.

Getter method

  • A getter method is used to get and save a specific fieldName class in a variable. A default getter method exists in all classes, but it can be overridden explicitly. The get keyword can be used to define the getter method.

  • Syntax:

  • 
      returnType get fieldName {
         // return the value
      }
    

Setter method

  • The setter method is used to set the data of a variable returned by the getter method. A default setter function exists in all classes, although it can be overridden explicitly.

  • The set keyword can be used to define the setter method.

  • Syntax :

  •   returnType set fieldName {
         // set the value
      }
    
class One {
    late String newName;

    String get getName {
        return newName;
    }

    set setName(String name) {
        newName = name;
    }

}

void main(){

    One jeet = One();
    jeet.setName = "Jeet";
    print("Welcome to ${jeet.getName}");

}
Welcome to Jeet

Exited.