Getter and Setters
Explore how to enhance property control in Dart classes by using getters and setters. Learn to encapsulate data with private backing fields and apply validation to protect object state. This lesson helps you write cleaner, safer Dart code following object-oriented principles.
We'll cover the following...
Up to this point, we accessed instance variables directly using the dot operator. This works perfectly for simple properties. As our programs grow, we often need more control over how a property is read or modified. For example, we might want to prevent an age from being set to a negative number. We achieve this level of control using getters and setters.
Getters and setters are special methods that provide read and write access to an object's properties. To use them effectively, we first need to hide the actual data inside the class so it cannot be bypassed.
Private backing fields
In Dart, we make a variable private by starting its name with an underscore ( ...