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){ = name
        self.age = age

var demo5 = Person(name: "Max", age: 34); = "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;

>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

Leave a Reply