Search code examples
flutterdartprovider

Using more than one provider in a flutter app


I have started using PROVIDER to manage state in my app. I followed tutorials and wrapped my Material app with ChangeNotifierProvider. Here's the code :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => ListsProvider(),
      child: MaterialApp(
        title: 'WordsApp',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        initialRoute: StartingPage.id,
        routes: {
          StartingPage.id: (context) => StartingPage(),
         
          RegistrationScreen.id: (context) => RegistrationScreen(),
        
        },
      ),
    );
  }
}

This provider called "ListsProvider" takes care of "providing" lists that need to be displayed on different screens. I have now created a second provider which I called "user_data_provider" and I now need to add it to my app too. It will take care of providing user data to many different screens.

How can I do that ?


Solution

  • To achive this you can use Multiprovider as shown below

    Add this to the top of your app. If you need these obj everywhere.

    @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider<user_data_provider>(
              create: (_) => user_data_provider(),
            ),
            ChangeNotifierProvider<ListsProvider>(
              create: (_) => ListsProvider(),
            ),
          ],
          child: Builder(
            builder: (BuildContext context) {
              
              return MaterialApp(
                //YOur code goes here
              );
            },
          ),
        );