Unaweza kutengeneza getter method kwa kutumia keyword get na unaweza kutengeneza setter method kwa kutumia keyword set. Hapa tutatumia arrow => function. (Rejea somo la aina za function)
class gari {
String? _aina;
int? _mwaka;
// Getter method
get model => _aina;
// Setter method
set model(model) => _aina = model;
// Getter method
get year => _mwaka;
// Setter method
set year(year) => _mwaka = year;
}
void main() {
var vehicle = gari();
vehicle.model = "Toyota";
vehicle.year = 2023;
print(vehicle.model);
print(vehicle.year);
}
Kuvalidate kwa kutumia getter:
Wacha tuone mfano wa validation. Angalia mfano hapo chini, kuna provate properties 2, sasa kwenye property name kama hutaweka kitu utaambiwa no name.
class NoteBook {
// Private properties
String _name;
double _prize;
// Constructor
NoteBook(this._name, this._prize);
// Getter to access private property _name
String get name {
if (_name == "") {
return "No Name";
}
return this._name;
}
// Getter to access private property _prize
double get prize {
return this._prize;
}
}
void main() {
// Create an object of NoteBook class
NoteBook nb = new NoteBook("Apple", 1000);
print("First Notebook name: ${nb.name}");
print("First Notebook prize: ${nb.prize}");
NoteBook nb2 = new NoteBook("", 500);
print("Second Notebook name: ${nb2.name}");
print("Second Notebook prize: ${nb2.prize}");
}
Mfano wa ku validate kwa kutumia setter:
Hapa chini pana program ya kuweka bidhaa na gharama(price). Sasa kama gharama ni chini ya dola 100, proram itakataa itakuletea error.
class NoteBook {
// Private properties
String? _name;
double? _prize;
// Setter to update the value of name property
set name(String name) => _name = name;
// Setter to update the value of prize property
set prize(double prize) {
if (prize < 100) {
throw Exception("Price cannot be less than 0");
}
this._prize = prize;
}
// Method to display the values of the properties
void display() {
print("Name: $_name");
print("Price: $_prize");
}
}
void main() {
// Create an object of NoteBook class
NoteBook nb = new NoteBook();
// setting values to the object using setter
nb.name = "Dell";
nb.prize = 160;
// Display the values of the object
nb.display();
}
Mwisho:
Kaika somo linalofuata tutakwenda kujifunza kuhus inheritance kwenye Dart OOP.