You get this error because your SecretProvider
instance is part of HomeScreen
which is not a parent of SecretScreen
.
In order, when you push a new page, this new page is not a descendent of the previous one so you can’t access to inherited object with the .of(context)
method.
Here the a schema representing the widget tree to explain the situation :
With a Provider on top of MaterialApp (the navigator) :
Provider MaterialApp HomeScreen -> push SecretScreen SecretScreen -> Here we can acces the Provider by calling Provider.of(context) because the context can access to its ancestors
With a Provider created in HomeScreen :
MaterialApp HomeScreen -> push SecretScreen Provider -> The provider is part of HomeScreen SecretScreen -> The context can't access to the Provider because it's not part of its ancestors
I hope my answer is pretty clear and will help you to understand what happens 😉
CLICK HERE to find out more related problems solutions.