Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

private properties in dart as compared in swift

in swift I can create private properties as in below

class Person {
    private(set) var name: String
    private(set) var age: Int

    init(name: String, age: Int){
        self.name = name
        self.age = age
    }
}

var demo5 = Person(name: "Max", age: 34);

demo5.name = "Min". ,<—— error Cannot assign to property: 'name' setter is inaccessible

But in dart this is allowing to set the value of _denominator , how can I stop this , or in dart from main I can access even private properties

main() {
  final frac = Fraction(1, 7);
  frac._denominator = 9; // <—— working
  print(frac._denominator); // <—— gives 9
}

class Fraction {
  int _numerator;
  int _denominator; //<— its private
  Fraction(this._numerator, this._denominator);

  int get numerator => _numerator;
  int get denominator {
    return _denominator;
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use final keyword while creating variable.

class Fraction {
  final int _numerator;
  final int _denominator;
  Fraction(this._numerator, this._denominator);

  ///set denominator(int value) => _denominator = value; //like this
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading