Search code examples
flutterdartflutter-providerflutter-change-notifier

How to use method from one Change notifier class in another change notifier class provider


I want to use fetchdata() in another provider method and initialise variables.

image


Solution

  • you can use MultiProvider with ChangeNotifierProxyProvider

    1. Action Class ( FirstModel )

       class FirstModel with ChangeNotifier {
       List<Strings> _names = ["Sat", "Sat2", "Sat3"];
      
       List<Strings> get names {
          return _names ;
       }
       }
      
    2. Action Class ( SecondModel )

       class SecondModel with ChangeNotifier {        
       SecondModel(this.firstModel);
      
       final FirstModel firstModel;
       List<Strings> getNames(){
          return firstModel.names;
       }
       }
      

    In main.dart just update the Multiprovider, example below

    void main() {
      runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider<FirstModel>(create: (_) => FirstModel()),
            ChangeNotifierProxyProvider0<SecondModel>(
              create: (BuildContext context) =>
                  SecondModel(Provider.of<FirstModel>(context, listen: false)),
              update: (BuildContext context, SecondModel secondModel) =>
                  SecondModel(Provider.of<FirstModel>(context, listen: false)),
            ),
          ],
          child: MyApp(),
        ),
      );
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    

    Similar other class also avilable... For More Information please refer below link...

    ChangeNotifierProxyProvider0 class API