0

I've created a ChangeNotifier and added it to the main.dart providers list like below:

ChangeNotifierProvider<AppState>(
    create: (context) => AppState(),
);

and I have a dialog which I wrap in ChangeNotifierProvider.value to have access to the provider inside dialog, like below:

showDialog(
    context: context,
    builder: (BuildContext context) {
      return ChangeNotifierProvider.value(
        value: AppState(),
        child: LanguageDialog(),
      );
    });
});

but the problem is that when I set some data in the provider state inside the dialog it works fine as long as I'm inside the dialog! when I close the dialog the state resets! and I have no idea why this happens. Also I've tried setting some state in another route and the result was that the state's data in that route was not the same as the dialog.

What am I doing wrong here?

Komeyl94
  • 161
  • 3
  • 15

2 Answers2

1

ChangeNotifierProvider.value creates a new AppState instance and passes to your dialog. It's not same as your global AppState instance. Instead of creating a new provider for your dialog you can access to Provider using Provider.of function inside your dialog.

var appState = Provider.of<AppState>(context);

You can either access to provider inside LanguageDialog or pass it through argument like this:

showDialog(
    context: context,
    builder: (BuildContext context) {
      return LanguageDialog(
        appState: Provider.of<AppState>(context);
      );
    }),
});
TheMisir
  • 4,083
  • 1
  • 27
  • 37
  • Thanks for the answer But I've tried using `Provider.of` inside the dialog but I always get the error that it couldn't find the provider above this widget, I also tried your second solution to pass the provider instance to the widget and it worked but there was one problem that the data was not updating inside the widget, what can I do about that? – Komeyl94 Sep 16 '20 at 05:15
  • @Komeyl94 probably there's an issue on your provider model. – TheMisir Sep 16 '20 at 09:21
  • https://stackoverflow.com/a/72335229/16407621 – Kaushal Kishore May 22 '22 at 06:19
0

The issue here is that the provider is scoped to the same routes and since you are navigating to a new route via dialog box, provider will not store the value when you exit that DialogBox.

Make sure to create your provider above the MaterialApp so that the provider is scoped to the entire app. You can specify it like this :-

ChangeNotifierProvider<AppState>(
    create: (context) => AppState(),
    child: MaterialApp(
       home: HomeScreen())
);
bharat8
  • 125
  • 2
  • 8