Dart Setters
The syntax for defining a setter looks as follows.
set field_name{
// set the value of the field_name here
}
The keyword set in the above declaration tells the compiler that this method is a setter. After that, we need to specify the name of the field whose value needs to be returned.
Implementation
The following is a sample program that will summarize the concept of getters and setters that has been discussed in this blog so far.
Code:
// Dart sample program to illustrate the use of getters and setters in Dart
class Ninja{
// Properties of the Ninja class
late String ninja_name;
late String ninja_batch;
late int ninja_roll_no;
// Getters
String get get_ninja_name{
return ninja_name;
}
String get get_ninja_batch{
return ninja_batch;
}
int get get_ninja_roll_no{
return ninja_roll_no;
}
// Setters
set set_ninja_name(String name){
ninja_name = name;
}
set set_ninja_batch(String batch){
ninja_batch = batch;
}
set set_ninja_roll_no(int roll_no){
ninja_roll_no = roll_no;
}
}
void main(){
Ninja obj = new Ninja();
// Using setter to set the values of the properties of the Ninja class
obj.set_ninja_name = "Mr X";
obj.set_ninja_batch = "A1";
obj.set_ninja_roll_no = 1;
// Using getters to obtain the values of the properties of the Ninja class
print("Ninja name: " + obj.get_ninja_name);
print("Ninja batch: " + obj.get_ninja_batch);
print("Ninja roll no: " + obj.get_ninja_roll_no.toString());
}
Output:
Ninja name: Mr X
Ninja batch: A1
Ninja roll no: 1
FAQs
-
Is it compulsory to add getter and setters to a Dart class?
No, it is not compulsory to add getters and setters to a Dart class as there exist default getters and setters in any Dart class.
-
Do I need to specify a return type in the setter function?
No, you do not need to specify a return type in the setter function. However, one needs to specify an appropriate return type in the getter function.
-
What are the alias names of getters and setters?
Getters are also known as accessors, whereas setters are also known as mutators in an alternate naming fashion.
Conclusion
In this article, we have extensively discussed getters and setters in Dart and saw a sample program having its implementation. You can also read the blog Dart Classes and Objects on the Coding Ninjas Website to learn more about classes and objects in Dart.
We hope this blog has helped you enhance your knowledge regarding Dart Getters and Setters methods. If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!