Search code examples
flutterprovider

how to use a provider for a single screen


Is there a way to have a provider for just a single screen i keep getting error could not find provider above widget tree..

i have tried the only solution i could find which was to wrap our widget in ChangeNotifier before navigation example.

Navigator.push( 
  context,
  MaterialPageRoute(
    builder: (context) =>
      ChangeNotifierProvider<
        SendingSMSChangeNotifier>(
          create: (_) =>
            SendingSMSChangeNotifier(),
              child:
                ProfileAdminScreen(
                ...

But this does not work, when i try to access the provider using Consmer i still get the error.

Lastly i saw a text in a stackoverflow answer that we shouldn't do this but the user failed to put why, in my naive mind putting in deep in the tree is good because then less files have to watch the provider, and i need it at the root of the widget at all, because this is just for a single screen and possible children of that screen, please enlighten me if i am wrong.

Thank you in advance.


Solution

  • If you're certain that the state you are managing is tightly coupled with a single screen and its immediate children, and you're not planning to extend the functionality significantly, it can make sense to have a provider specific to that screen. To do this Wrap the whole screen (or its subtree) with the provider as you initially showed:

        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ChangeNotifierProvider<SendingSMSChangeNotifier>(
              create: (_) => SendingSMSChangeNotifier(),
              child: ProfileAdminScreen(),
            ),
          ),
        );
    

    In the ProfileAdminScreen or its children, you can use Consumer to access the provided data:

        Consumer<SendingSMSChangeNotifier>(
          builder: (context, sendingSMSProvider, _) {
            // Use the provided data here
            return YourWidgetUsingTheData();
          },
        )
    

    Just ensure that the state managed by this provider remains specific to this screen and doesn't end up being shared with other parts of your app.