1

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.

hmarat
  • 43
  • 6

3 Answers3

3

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),
 );
hmarat
  • 43
  • 6
  • I have the same issue. In my case I have to preload a lot that I give to MyApp. Should I preload it again before I run Navigator to MyApp(mappedJson, initialUser, products)? In your case it is the token, in my case products etc. – desmeit Jan 25 '23 at 11:51
0

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;
          },
        ),
Oreofe Solarin
  • 286
  • 5
  • 13
  • It's not my first day in flutter :) I don't want to update some data in one MultiProvider, and there can be more than 10 providers. I want to reinitialize it, as it will be in the first build time. – hmarat Jul 29 '21 at 07:05
0
ChangeNotifierProvider(
          create: (_) => UserFeedViewModel(),
          child: Expanded(
            child: Consumer<UserFeedViewModel>(
                builder: (context, userFeedViewModel, child) =>
                    _ui(userFeedViewModel)),
          ),
        ), 

I created the provider when the widget is created. I don't know if it's the right way but it did work. Curious to know your thoughts