简体   繁体   中英

How reinitialize flutter MultiProvider's all providers data?

In my application, I have many providers, for instance notifications, auth, profile, conversations, trips, etc... And now I need to reinitialize all providers, when user logout. Otherwise old user data will still stay in provider, and new user will get them.

You can call the providers and clear all the user's data. For example: You can call your authProvider.logOut() , all still depends on your project structure.

RaisedButton(
          child: const Text("Logout"),
          onPressed: () {
            final Auth auth = Provider.of<Auth>(context, listen: false);
            auth.isAuthentificated = false;
          },
        ),

After spending my day, I solved the problem in this way. It is the most elegant way I could do. So after logout, you have to remove all screens and navigate to the root widget, within which your Provider or MultiProvider is created, and so your provider or all your providers inside MultiProvider will be recreated, and all data will be reinitialized

Navigator.of(context).pushAndRemoveUntil<T>(
  MaterialPageRoute(
      builder: (_) => MyApp(),
  ),
  (_) => false,
);

Where MyApp is the root widget, which is passed as parameter in your main function in main.dart.

 runApp(
   MyApp(token: token),
 );

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