请求的导航器操作使用了不包含导航器的上下文。 (Builder函数将不会显示MainPage())

时间:2020-04-20 13:45:06

标签: android-studio flutter dart navigation builder

按下按钮后,我得到错误代码“请求的导航器操作使用了不包含导航器的上下文。”我用于导航的代码在RegisterPage中,并且通过builder函数应显示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();
  }

1 个答案:

答案 0 :(得分:0)

这是因为使用导航器(RegisterPage)的窗口小部件在窗口小部件树中与创建导航器(MaterialApp)的窗口小部件处于同一级别

解决方案: 在RegisterPage下方放置MaterialApp,以便能够使用其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'),
                )),
          ),
        )
    );
  }
}