void main() {
CarCarCar car1 = CarCarCar('Toyota', 'Corolla', 1983);
CarCarCar car2 = CarCarCar('', '', 2014);
List<CarCarCar> cars = [car1, car2];
for (var car in cars) {
print(car.getCarModel());
}
}
class CarCarCar {
String _car;
String _model;
int uretimYili;
CarCarCar(this._car, this._model, this.uretimYili);
String get car => _car;
set car(String car) {
if (car.isNotEmpty) {
_car = car;
} else {
throw ArgumentError('Car değeri bulunamadı: $car');
}
}
String get model => _model;
set model(String model) {
if (model.isNotEmpty) {
_model = model;
} else {
throw ArgumentError('Model değeri bulunamadı: $model');
}
}
String getCarModel() {
return '$_car, $_model, $uretimYili';
}
}
The code outputs:
Toyota, Corolla, 1983
, , 2014
I expected the code to throw an error since I have defined setters which validates car and model. Since I try set both car and model to empty Strings, the validation should have failed.
I want to know different ways to solve the problem.
You have to know the difference between
getter-setterandconstructorin your code, the validation is on your setter, it will throw error if you are set the value to the
instanceeg:
result:
if you want to avoid empty value from
constructor, then you can useassertit will throw assertion failed when its empty string
eg: