0

This error has a lot of solutions. But I am getting this error. I tried several ways at this site. but could not get a solution. This is my code

@override
Widget build(BuildContext context) {

 // TODO: implement build
 SystemChrome.setEnabledSystemUIOverlays([]);

 return MaterialApp(
  routes: <String, WidgetBuilder>{
    '/homepage': (context) => MyApp(),
    '/loginpage': (BuildContext context) => new LoginPage()
  },
  home: Scaffold (
    body: Center(
      child: GestureDetector(
        onTap: () {

        Navigator.of(context).pushNamed('/loginpage');
        },
        child: Image(
          width: 100.0,
          height: 100.0,
          image: AssetImage('assets/images/icon.png'),
        ),
      )

    ),

  ),
 );
}
  • use [MaterialApp.navigatorKey](https://api.flutter.dev/flutter/material/MaterialApp/navigatorKey.html) property – pskink May 16 '20 at 03:06

3 Answers3

1

You can wrap your Scaffold with a Builder widget and it will provide you a context.

Here is the updated code

@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);

return MaterialApp(
  routes: <String, WidgetBuilder>{
    '/homepage': (context) => MyApp(),
    '/loginpage': (BuildContext context) => new LoginPage()
  },
  home: Builder(
    builder:(context)=>Scaffold (
      body: Center(
        child: GestureDetector(
          onTap: () {
            Navigator.of(context).pushNamed('/loginpage');
          },
          child: Image(
            width: 100.0,
            height: 100.0,
            image: AssetImage('assets/images/icon.png'),
          ),
        ),
       ),
      ),
     ),
   );
 }

Hope this helps!

Shubham Gupta
  • 1,917
  • 1
  • 10
  • 16
0

this is happening because the context you are using it doesn't have a material app which is needed for the navigator to work, the context used in build widget is from the parent that got sent to it's child so in this case the parent is your main app class which it doesn't have a material app, so you can either use the Builder widget as suggested in one of the answers or you can create a separate widget and assign it to the home parameter, like this:

your statless widget:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold (
      body: Center(
          child: GestureDetector(
            onTap: () {
              Navigator.of(context).pushNamed('/loginpage');
            },
            child: Image(
              width: 100.0,
              height: 100.0,
              image: AssetImage('assets/images/icon.png'),
            ),
          )

      ),

    );
  }
}

using it as the home parameter home: MyHomePage().

hewa jalal
  • 952
  • 11
  • 24
0

You can see the answer at this link

https://stackoverflow.com/questions/44004451/navigator-operation-requested-with-a-context-that-does-not-include-a-navigator
redgreen
  • 143
  • 1
  • 10