How to control a dialog from provider?

Viewed 1933

I'm very new to Flutter. I'm trying to learn the Dart syntax and Flutter structure and conventions. It's quite fun. I'm JS developer, react, react native, node.js base. So, I think I'm used to the declarative structure and design.

I'm building a small toy project using the provider. Most global variable and state is in the global state and providing to the whole app. Actually, one of my problems is to open a dialog. I know how to open a dialog with showDialog() method. But, I want to open it by the state of the provider. eg. isOpenCustomDialog state in the provider.

Widget build(BuildContext context) {
  var isOpenCustomDialog = Provider.of<Store>(context).isOpenCustomDialog;

  // it throws error
  if(isOpenCustomDialog) showDialog( ... )

  return ...
}

I tried several ways, but no gains and I'd like to know what is the best convention for this purpose.

1 Answers

It is not good practice to open dialogs or call functions within method builds. That's because the Flutter can be rebuilt at any time, and a setState or several, can trigger side effects. An perhaps easier and more practical approach for you is to call your dialog directly from your provider class, since you depend on a state for that. You could do this by sending your context to your class (I think it's an ugly solution) or simply use this package that allows you to open dialogs from anywhere in your code, as you don't need context.

https://pub.dev/packages/get

So in your Store class, you could use the following:

Get.dialog(SimpleAlertDialog());

However, if you just want to remove this error, maybe watching the end of the construction to call the dialog also helps you:

Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback((_) {
 if(isOpenCustomDialog) showDialog( ... )
});
Related