Provider for Single View Flutter

Issue

I’m working with the provider package for Flutter. What I want to accomplish is to have a simple provider just for one view or page. So I tried the following in my widget:

Widget build(BuildContext context) {
    return ChangeNotifierProvider<MyModel>(
      create: (_) => MyModel(),
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            'Screen 1',
          ),
        ),
        body: _buildBody(),
      ),
    );
  }

but when I try to access the provider using a Provider.of<MyModel>(context, listen: false).value in my _buildBody() method I get the error:

Could not find the correct Provider above this MyPageWidget

When I move the declaration of the provider to where I declare my App above this Widget it works. Unfortunately this makes the provider public for all of my views to access which is not what I want. How can I make a provider that just can be accessed within that one view or widget. Thanks for any help.


Note: I tried this answer but I’m still getting the same result.

Edit: I could use a Consumer at the top of my widget tree, but doesn’t that cause the page to rebuild too much if my whole widget tree is in the Consumer. Further, what if I need to use Provider.of(...)?

Solution

I finally figured out a solution to this that doesn’t require rebuilding the whole widget tree when a change happens like @GJJ2019 answer. When I declare the route, for example:

'/': (context) => MyScreen();

I wrap MyScreen with the ChangeNotifierProvider for example:

'/': (context) => ChangeNotifierProvider<MyModel>(
  create: (_) => MyModel(),
  child: MyScreen()),

So instead of declaring the provider in the widget/screen that it was being used, declare the provider where you declare the route.

Answered By – Gabe

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.