How to display a dialog from ChangeNotifier model

Issue

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?

Solution

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
}

Answered By – CopsOnRoad

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.