0

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.

mbakabilal
  • 189
  • 2
  • 12
  • Riverpod doesn't look to the context to find the values. You might consider Riverpod in new code to avoid this problem in the future, or a refactoring of this code. – Randal Schwartz Aug 21 '23 at 17:07
  • Does this answer your question? [Could not find the correct provider above this widget](https://stackoverflow.com/questions/57124258/could-not-find-the-correct-provider-above-this-widget) – OMi Shah Aug 21 '23 at 23:46

1 Answers1

1

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.