Mastering Dart: A Comprehensive Guide on Getters and Setters

Mastering Dart: A Comprehensive Guide on Getters and Setters

Introduction

Imagine your data as a vault filled with priceless gems (valuable information, obviously). You wouldn't just leave it wide open, would you? Getters and setters are like the vault's security system, granting access only to authorized personnel (your code!)

Getter and setter methods are the class methods used to manipulate the data of the class fields. Getters are special methods used to retrieve and access the value of a particular field within an object whereas setters occupy a crucial role as the designated modifiers of data stored within objects.

No need to worry! We'll explore these concepts in much greater detail.

Why getters and setters?

Imagine your code as a vault safeguarding precious data like user passwords or product prices. Default getters and setters act as your initial security guards, granting access to this data. But what if they're not enough? Let's explore their limitations and how custom guardians can rise to the challenge.

class Vault {
  int balance = 1000;
  String password = 'helloWorld';
}

void main() {
  Vault vault = Vault();
  vault.balance = 0;
  print("Account Balance: ${vault.balance}");
  vault.password = 'Hacked!';
  print(vault.password);
}
Output:
Account Balance: 0
Hacked!

Witness how effortlessly values can be accessed and modified. This is where getters and setters play a crucial role.

Let's enhance the security of your vault.

Getter Method in Dart

It is utilized to fetch a specific field from a class and store it in a variable. Although all classes come with a default getter method, it can be explicitly overridden. The getter method can be defined by employing the get keyword, as shown below:

Syntax:

return_type get field_name{
    ...
}

or

return_type get field_name =>  ...

Why custom getter over default getter ?

class Vault{
  String secret = 'Coke secret formula';
}

void main() {
Vault vault = Vault();
print(vault.secret);
}
Output:
Coke secret formula

As evident, anyone can access the Coke's secret and create their own version. How can we ensure the protection of secrets within our Vault class?

class Vault {
  String _secret = 'Coke secret formula';
  bool accessible;
  Vault(this.accessible);
  String get secret => accessible? _secret : "Access denied!";
}

void main() {
  Vault vault = Vault(false);
  print(vault.secret);
}
Access denied!

To ensure the "secret formula" remains hidden, we:

  1. Lock it up: By adding an underscore, we make it private, accessible only within the Vault class.

  2. Control access: We create a custom "getter," that checks if someone is authorized to see the formula before granting access.

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 setkeyword as:

Syntax:

set field_name{
    ...
}

Why custom setter over default getter ?

class Vault {
  String secret = 'Coke secret formula';
}

void main() {
  Vault vault = Vault();
  vault.secret = 'Modified recipe of Coke';
  print(vault.secret);
}
Output:
Modified recipe of Coke

Notice how effortlessly someone can modify the Coke's recipe and introduce an altered version.

Let's explore how we can resolve this

class Vault {
  String _secret = 'Coke secret formula';
  bool accessible;
  Vault(this.accessible);
  String get secret => accessible ? _secret : "Access denied!";
  set secret(String setSecret) {
    if (accessible) {
      _secret = setSecret;
    }
  }
}

void main() {
  Vault vault = Vault(true);
  vault.secret = 'New Secret';
  print(vault.secret);
}
Output:
New Secret //Vault(true)
Access denied! //Vault(false)

The set secret setter acts as a vigilant gatekeeper. It checks if the user is authorized (accessible) before allowing any changes to the formula. Unauthorized attempts are denied, keeping the secret safe.

Conclusion

Setters and getters in Dart and Flutter are like secret agents, silently working behind the scenes to ensure your code's safety and efficiency. With these powerful tools, developers gain fine-tuned control over class properties, fostering a world of encapsulation and enhanced functionality.

By leveraging setters and getters, code readability is boosted, data integrity is safeguarded, and even calculated properties can be introduced seamlessly. Armed with the knowledge of best practices, such as encapsulating private properties and adhering to naming conventions, developers unlock the full potential of setters and getters in their Dart and Flutter projects, empowering them to create robust and reliable software solutions.

Further Reading

Thank You!

If you have any queries please comment down below.
Happy learning, everyone!