Search code examples
android-studioflutterdartnavigationbuilder

Navigator operation requested with a context that does not include a Navigator. (Builder function wont display MainPage())


As soon as I press the button I get the error code "Navigator operation requested with a context that does not include a Navigator." Code im using to navigate is in the RegisterPage and by the builder function should be displaying the MainPage.

void main() => runApp(RegisterPage());

class RegisterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      appBar: AppBar(
        title: Text('Register Your Account'),
        centerTitle: true,
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.of(context)
                .push(
              MaterialPageRoute(
                  builder: (context) => MainPage()
              ),
            );
          },
          child: Text('Sign in as guest'),
        )),
      )
    );
  }
}

  class MainPage extends StatefulWidget{
  String get title => "Cykla i stockholm";

  MapPage createState()=> MapPage();
  }

Solution

  • That's because the widget which uses the navigator (RegisterPage) is at the same level in the widget tree with the widget which creates the navigator(MaterialApp)

    SOLUTION: make the RegisterPage below MaterialApp in order to be able to use its context:

    class RegisterPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
              appBar: AppBar(
                title: Text('Register Your Account'),
                centerTitle: true,
                backgroundColor: Colors.green,
              ),
              body: Builder(
                builder: (ctx)=> Center(//this context here has access to Navigator
                    child: RaisedButton(
                      onPressed: () {
                        Navigator.of(ctx)
                            .push(
                          MaterialPageRoute(
                              builder: (context) => MainPage()
                          ),
                        );
                      },
                      child: Text('Sign in as guest'),
                    )),
              ),
            )
        );
      }
    }