Home > Blockchain >  Flutter - Navigator.push() giving error "Context does not include a Navigator" on extends
Flutter - Navigator.push() giving error "Context does not include a Navigator" on extends

Time:01-21

I've been creating a flutter app for a society and i'm using flutter. I have created two "window" (I don't really know the technical terms on flutter), The first one will display correctly with a button to switch on the second. If you click on the button the other window will display correctly. But, i want to use DeepLinks (for the notifications), and if i click on the link, the redirect in the _AccueilPageState to the Pub class (I'm using

Navigator.push(context,MaterialPageRoute(builder: (context) =>  Pub()));

I got the error

Navigator operation requested with a context that does not include a Navigator

Someone can explain me what is wrong ? And maybe how to fix this issue ! Thanks, Here you can see the hierachi of my code (I can't show all of it because of confidentiality):

void main() async{...}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return this;
  }
  @override
  State<StatefulWidget> createState() => _AccueilPageState();
}
//Loading properties for MyApp(with the navigator.push in it)
class _AccueilPageState extends State<MyApp>{...}

//class loading FenetrePrincipale
class WebView extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home : FenetrePrincipale(),
    );
  }
}
//Pub that return a MaterialApp(home:Builder:(context)=>Scaffold())
class Pub extends StatelessWidget{...}

//FenetrePrincipale that return a Scaffold
class FenetrePrincipale extends StatelessWidget{...}

//When on FenetrePrincipale we can push a button to open Pub but if you go trough a deeplink : _AccueilPageState
//Does not redirect on Pub and put the error :
//"Navigator operation requested with a context that does not include a Navigator"


CodePudding user response:

  1. Create a global key for the navigator so you can access it from anywhere in the application:
final GlobalKey<NavigatorState> myNavigatorKey = GlobalKey<NavigatorState>();
  1. Assign it to your app when creating MaterialApp:
return MaterialApp(navigatorKey: myNavigatorKey,...);
  1. Use it when pushing routes:
myNavigatorKey.currentState?.pushNamed(...);
  •  Tags:  
  • Related