0

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!

Shahood ul Hassan
  • 745
  • 2
  • 9
  • 19

1 Answers1

0

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;
  }
}
Hossein Yousefi
  • 889
  • 8
  • 18
  • Thanks for pointing in the right direction. Following your lead, I came across this nice article on `late` keyword: https://blog.gskinner.com/archives/2021/03/flutter-lazy-instantiation-with-the-late-keyword.html just to realize that I can also initialize the variable as `late final CalculationDao _calculationDao = db.calculationDao;` and keep the constructor intact as `CalculationViewModel({required super.context});`. Before that, I considered using `late` as something extremely risky and prone to errors. – Shahood ul Hassan Nov 05 '22 at 09:45