Search code examples
flutterdartdart-async

How to wait for a method that is already being executed?


I'm developing a Flutter app which has some tabs inside, each of them depend on the database that is loaded on the first run. State is stored in a ScopedModel.

On every tab I have this code:

@override
void initState() {
  super.initState();

  loadData();
}

void loadData() async {
    await MyModel.of(context).scopedLoadData();

    _onCall = MyModel.of(context).onCall;

    setState(() {

    });
  }

And this is the code snippet that matters for the ScopedModel:

Future<Null> scopedLoadData() async {

  if (_isLoading) return;

  _isLoading = true;

  (...)

  _isLoading = false;

}

If the user waits on the first tab for a few seconds everything is fine, since Database is loaded. However, if the user switches tabs right after app launch, the method scopedLoadData is still being executed so that I get a runtime error ("Unhandled Exception: NoSuchMethodError: The method 'ancestorWidgetOfExactType' was called on null.").

This exception happens because the scopedLoadData has not yet been completed. So I'm looking for a way to wait for a method that is still being executed.

Thanks!


Solution

  • I solved the exception by getting rid of every:

    setState(() { });
    

    and implementing ScopedModelDescendant on every relevant tab on top of using notifyListeners() at the end of the database loading method.

    This pulls the responsibility from the tabs for updating views and gives it to the scopedLoadData().