Setter not running as part of constructor

50 Views Asked by At
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.

1

There are 1 best solutions below

1
pmatatias On

You have to know the difference between getter-setter and constructor

  • this is constructor:
CarCarCar(this._car, this._model, this.uretimYili);
  • this is getter and setter
String get car => _car;
set car(String cr) {
  if (cr.isNotEmpty) {
    _car = cr;
  } else {
    throw ArgumentError('Car değeri bulunamadı: $car');
  }
}

in your code, the validation is on your setter, it will throw error if you are set the value to the instance

eg:

 CarCarCar car1 = CarCarCar('Toyota', 'Corolla', 1983);

car1.car = ''; // set car value with empty string

result:

enter image description here


if you want to avoid empty value from constructor, then you can use assert

class CarCarCar {

  CarCarCar(this._car, this._model, this.uretimYili)
      : assert(_car.isNotEmpty || _model.isNotEmpty);

it will throw assertion failed when its empty string

eg:

void main() {
  CarCarCar car1 = CarCarCar('Toyota', 'Corolla', 1983);
  CarCarCar car2 = CarCarCar('', '', 2014);

enter image description here