Home > database >  How to initialize an instance variable in constructor of child class, from an instance variable of p
How to initialize an instance variable in constructor of child class, from an instance variable of p

Time:11-06

Please consider these parent and child classes of Java and see how calculationDao has been initialized in CalculationRepository on the basis of instance variable db of parent class SqliteRepository :

Parent class:

public class SqliteRepository {

    final MyDatabase db;

    public SqliteRepository(@NonNull Application application) {
        db = MyDatabase.get(application);
    }
}

Child class:

public class CalculationRepository extends SqliteRepository {

    private final CalculationDao calculationDao;

    public CalculationRepository(@NonNull Application application) {
        super(application);
        calculationDao = db.calculationDao();
    }
}

I want to achieve the same thing in Dart. Here are the Dart classes:

Parent class:

class SqliteRepository {
    final MyDatabase db;

    SqliteRepository({required BuildContext context}) : db = MyDatabase.instance;

}

Child class:

class CalculationRepository extends SqliteRepository {
    final CalculationDao _calculationDao;
    
    CalculationRepository({required super.context}) : _calculationDao = db.calculationDao;

}

However, this gives the following error:

The instance member 'db' can't be accessed in an initializer. (Documentation)

Try replacing the reference to the instance member with a different expression

I've spent a lot of time searching for a solution but in vain.

Could anyone please guide me how I can initialize this final variable calculationDao in the constructor of CalculationRepository?

Any help would be a great help!

CodePudding user response:

You can use db inside the constructor itself. But since you're not specifying the value of the final property _calculationDao at the time of initialization, you can mark it with late:

class CalculationRepository extends SqliteRepository {
  late final CalculationDao _calculationDao;

  CalculationViewModel({required super.context}) {
    _calculationDao = db.calculationDao;
  }
}
  •  Tags:  
  • dart
  • Related