Sarvesh Dalvi
Sarvesh Dalvi

Reputation: 2678

Why does using the provider class gives an error after moving to next screen after navigator.push()?

So I recently learned the if we are not using provider above Material App widget, then if we try to access the provider value after doing a Navigator.push() it will throw an exception :

Unhandled Exception: Error: Could not find the correct Provider above this Consumer Widget

I got to know that when we use Navigator.push(), it changes the route and hence the current widget doesn't belong under the Provider's tree. But we also pass the current widget's build context in Navigator.push(context,(_) => NewWidget()) too right ?

So isn't this passed context used in the new Widget built after Navigator.push()? The information provided after the error stated that the widget should be using the some context of the provider's source. So if I am satisfying this condition then why am I still getting this error ?

Thankyou in advance for answering :)

Upvotes: 2

Views: 371

Answers (1)

Rustem Kakimov
Rustem Kakimov

Reputation: 2671

context is used here to find the closest Navigator instance here. It's a shorthand for Navigator.of(context).push(route).

context can be thought of as a position in the widget tree. Provider.of(context) will return the nearest provider above the given context position.

When a route is pushed, MaterialApp widget will swap the tree. You can think of it as the route widget becoming a direct child of MaterialApp. So, above your route widget is a MaterialApp, and then nothing... So, it can't find the provider.

Therefore, you have to wrap your route widgets with another provider.

Navigator.of(context).push(MaterialPageRoute(
  builder: (BuildContext context) => Provider<Something>(
    create: ...,
    child: MyPage(),
  ),
));

Upvotes: 2

Related Questions