Dart Validating Data using Setter
Validating Data Using Setters in Dart
In Dart, setters are methods that allow you to modify the value of a class's private field. One powerful feature of setters is that they can be used to validate or transform data before it is stored in the private field.
When you want to enforce constraints or validation rules on the data being assigned to a field, you can do so within the setter. For example, you might want to ensure that an age is always a positive integer or that a name isn't empty.
Steps to Validate Data Using Setters:
- Define a private field in your class.
- Create a setter for that field.
- Inside the setter, add validation logic to check if the input data is valid.
- If the data is valid, assign it to the private field.
- If the data is invalid, you can either throw an exception, print an error, or handle it in another way.
Example of Validating Data Using Setters in Dart
Let’s consider a class Person
where we need to validate the age and name before assigning them to the private fields.
Code Example:
Explanation:
Private Fields:
_name
and_age
are private fields. These are the fields that store the data for thePerson
object.
Getters:
String get name => _name;
is the getter for the_name
field, allowing us to access the name of the person.int get age => _age;
is the getter for the_age
field, allowing us to access the age.
Setters with Validation:
set name(String newName)
is the setter for the_name
field. It checks if the new name is an empty string. If it is, an error message is printed. Otherwise, the name is assigned to the private_name
field.set age(int newAge)
is the setter for the_age
field. It ensures that the age is greater than 0. If a negative or zero value is provided, an error message is printed. Otherwise, the age is assigned to the private_age
field.
Displaying Information:
displayInfo()
is a method that prints the current name and age of the person. It is used to show the updated information after changing the fields.
Invalid Inputs:
- When trying to set invalid data, such as an empty name (
person.name = '';
) or a negative age (person.age = -5;
), the setters print an error message. - If valid data is provided, it updates the fields and the changes are reflected when calling
displayInfo()
.
- When trying to set invalid data, such as an empty name (
Output:
Summary:
- Setters allow you to modify the value of private fields and are a great place to implement validation logic.
- In the example above, we used the setter for
name
to check if the new name is empty and the setter forage
to ensure that age is a positive number. - By using setters, we can enforce data integrity and ensure that only valid data is assigned to the object's fields. If the data is invalid, we can display an error message or handle it according to the requirements.