flutterflutter-change-notifier

Can a ChangeNotifier listen to another ChangeNotifier's state flutter


I have two classes, AuthAPI and UserUpdate. both extends ChangeNotifier. The update() method under UserUpdate updates the the user.

I am trying to trigger the AuthAPI class when the Update class is done updating the user.

class AuthAPI extends ChangeNotifier {
   late String _currentUser;
   String get name => _currentUser;

}

class UserUpdate extends ChangeNotifier {
  void update(User currentUser) {
   try{
    // some api 
   } catch(e){
    // some error
   }
    notifyListeners(); 
  }
}

I tried to do this by using a condition that watches the Update class in the frontend and try to trigger AuthAPI afterwards. However, this did not work.

I am lost or what? 😂


Solution

  • You need to use ChangeNotifierProxyProvider. In your case it would be something like:

    List<SingleChildWidget> providers;
    
    providers = [
        ChangeNotifierProvider<AuthAPI>(create: (_) => AuthAPI()),
        ChangeNotifierProxyProvider<AuthAPI, UserUpdate>(
                create: (_) => UserUpdate(),
                update: (context, authAPI, previous) =>
                    previous!
                      ..update(authApi))
    ];
    
    runApp(MultiProvider(providers: providers, child: const MyApp()));