jakub
jakub

Reputation: 3854

Waiting until constructor / init function will initialize members of the class

Currently, when I'm running await myService.getItem() I'm getting a null pointer exception because _box isn't initialized yet. How to be sure, that my _initialize function is finished before calling any other function from MyService?

class MyService {

  Box<Item> _box;

  MyService() {
    _initialize();
  }

  void _initialize() async {
    _box = await Hive.openBox<Storyboard>(boxName);
  }

  Future<Item> getItem() async {
    return _box.get();
  }
}

For creating MyService I'm using Provider like:

final myService = Provider.of<MyService>(context, listen: false);

Upvotes: 1

Views: 430

Answers (1)

nvoigt
nvoigt

Reputation: 77354

You cannot. What you can do it make sure your method depending on initialization waits until it's really done before continuing:

class MyService {
  Box<Item> _box;
  Future<void> _boxInitialization;

  MyService() {
    _boxInitialization = _initialize();
  }

  Future<void> _initialize() async {
    _box = await Hive.openBox<Storyboard>(boxName);
  }

  Future<Item> getItem() async {
    await _boxInitialization; // this might still be ongoing, or maybe it's already done
    return _box.get();
  }
}

I'm not really happy with that solution, it's feel a little... off, but it would do the trick.

Upvotes: 1

Related Questions