Why do we need the context to Navigate?
--
When you are fresh new on the flutter world you may find a little cumbersome the navigation process. I’m almost sure you found yourself
trying to navigate to another page in a situation where you don’t have a BuildContext to use. On this article i’ll try to explain why you need the context to navigate.
If you have some experience with Flutter you already hear something like that: “In Flutter everything is a widget”. That couldn’t be more true,
and guess what the Navigator is a Widget too!
Here’s the proof:
Navigator is a StatefulWidget that is used to manage the app’s stack of pages. Navigator is a Widget created by Flutter when we create a MaterialApp and
because we need access to the state of this Navigator to do the
navigation in different parts of the app, we have to figured a way to get this state from anywhere on our app.
Well, i said that sometimes, Flutter is our friend. It gives us a way to retrieve the state of any StatefulWidget. Just do:
context.findAncestorStateOfType<NavigatorState>();
And Flutter gives us a convenient static method on the Navigator class to do this
static NavigatorState of(BuildContext context)
So this is the reason we have to give a BuildContext to the Navigator so it can find the nearest NavigatorState and perform the navigation.
That’s ir for today guys, if you have some questions or suggestions let me know.
Thanks for reading!