How do getters and setters change properties in Dart?

后端 未结 2 1443
不思量自难忘°
不思量自难忘° 2020-12-13 17:38

I am struggling with the concept of getters and setters in Dart, and the more I read, the more I cannot grasp the underlying purpose. Take for example the following code:

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 18:29

    Instance variables in Dart have implicit getters and setters. So for your example code, it will operate in exactly the same way, since all you have done is changed from an implicit getter and setter to an explicit getter and setter.

    The value of explicit getters and setters is that you don't need to define both if you don't want. For instance we can change your example to only define a getter:

    main() {
        Car car = new Car();
        print(car.doors);  // 4
        car.doors = 6; // Won't work since no doors setter is defined
    }
    
    class Car {
        int _doors = 4;
        int get doors => _doors;
    }
    

    Additionally, you can also add extra logic in a getter or setter that you don't get in an implicit getter or setter:

    class Car {
        int _doors = 4;
        int get doors => _doors;
        set doors(int numberOfDoors) {
          if(numberOfDoors >= 2 && numberOfDoors <= 6) {
            _doors = numberOfDoors;
          }
        }
    }
    

提交回复
热议问题