2

In my project, when ChangeNotifier class receives a status it sets up a boolean and calls notifyListeners(). In my main build() function, I then check the pending-boolean and display the dialog accordingly - but I am only able to display the dialog by giving it a small delay in the build method - it seems the context is missing.


TL;DR:

Is there any way to display a dialog from within the ChangeNotifier class?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
fideldonson
  • 581
  • 3
  • 15

1 Answers1

2

Even if you could do that by just passing a BuildContext, you shouldn't, because you'd be coupling your ChangeNotifier to specific cases only.

Let's say this is your model:

class Model extends ChangeNotifier {
  bool _loading = false;

  bool get loading => _loading;

  void update(bool value) {
    _loading = value;
    notifyListeners();
  }
}

And say, you're updating loading value on a button press using:

final model = Provider.of<Model>(context, listen: false);
model.update(true);

You should perform your logic here itself, or maybe you are listening to this model somewhere else in your project with:

final model = Provider.of<Model>(context);

You then should show dialog by checking:

if (model.loading) {
  // show dialog
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • This is actually how it is set up right now. The problem is that the call to show the dialog fails - apparently because the context is not available at the time it is called (first up in the build method). – fideldonson May 20 '20 at 12:02
  • 1
    Yes you cant show the dialog before widgets have been rendered on the screen. The solution is to use SchedulerBinding.instamce.addPostFraneCallback in your initState and then call the dialogz you would have q valid contact there. Sorry for typos, i am using phone at this time. – CopsOnRoad May 20 '20 at 12:13