按下按钮后,我得到错误代码“请求的导航器操作使用了不包含导航器的上下文。”我用于导航的代码在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();
}
答案 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'),
)),
),
)
);
}
}