Reputation: 171
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?
Upvotes: 0
Views: 2398
Reputation: 125
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())
);
Upvotes: 0
Reputation: 4279
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);
);
}),
});
Upvotes: 1