Setters And Getters In Dart Programming

Setters And Getters In Dart Programming

SETTERS AND GETTERS

In Dart, setters and getters are methods that are used to set and get the values of properties in a class. Setters and getters are used to control how a property is accessed and modified, and they are typically used in classes to provide a consistent and predictable interface for working with an object's properties.

Setter

A setter is a method that is used to set the value of a property. Setters are typically defined using the set keyword followed by the property name. For example, you could define a setter for the name property of a Dog class like this:

class Dog {
  String _name;

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

In this example, we define a setter for the name property of the Dog class. The setter is defined using the set keyword, and it takes a single argument called newName which represents the value that we want to set the name property to. Inside the setter, we simply assign the value of newName to the _name property, which is the private field that holds the actual value of the name property.

To use the setter, you simply assign a value to the name property of a Dog object using the = operator. For example:

// Create a new Dog object
Dog dog = new Dog();

// Set the name of the dog using the setter
dog.name = 'nevil';

In this example, we create a new Dog object and then set the name property of the dog to "nevil" using the setter. The setter takes care of assigning the value to the _name property and ensures that the value is set correctly and consistently.

Getter

A getter is a method that is used to get the value of a property. Getters are typically defined using the get keyword followed by the property name. For example, you could define a getter for the name property of a Dog class like this:

class Dog {
  String _name;

  get name {
    return _name;
  }
}

In this example, we define a getter for the name property of the Dog class. The getter is defined using the get keyword, and it does not take any arguments. Inside the getter, we simply return the value of the _name property, which is the private field that holds the actual value of the name property.

To use the getter, you simply access the name property of a Dog object using the. operator. For example:

// Create a new Dog object
Dog dog = new Dog();

// Set the name of the dog using the setter
dog.name = 'nevil';

// Print the name of the dog using the getter
print(dog.name); // Output: nevil

In this example, we create a new Dog object, set the name property of the dog using the setter, and then print the name property using the getter. The getter takes care of returning the value of the _name property and ensures that the value is returned consistently and correctly.

Thanks for reading my article hope you find it useful