简体   繁体   中英

Flutter provider values reset after closing the dialog

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?

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);
      );
    }),
});

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())
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM