1 、问题
用Flutter写了页面跳转,提示错误如下
Navigator operation requested with a context that does not include a Navigator.
2 、我的代码
void main() { runApp(MyApp1()); } class MyApp1 extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'open url', home: Scaffold( appBar: AppBar( title: Text('hello flutter'), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ FlatButton( child: Text("go to new page"), textColor: Colors.blue, onPressed: () { Navigator.push(context, MaterialPageRoute( builder:(context) => NewPage())); }, ), ], ), ), ); } } class NewPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("hello word"), ), body: Center( child: Text("this is new page"), ), ); } }
3、原因
Navigator operation requested with a context that does not include a Navigator.
说明这个context上下文不一致,我们看下Navigator的继承关系
1. class Navigator extends StatefulWidget { 2. }
但是我的代码是这样的
1. class MyApp1 extends StatelessWidget { 2. }
我们需要使用StatefulWidget的Context
4、解决办法
void main() { runApp(MaterialApp( title: "Navigation basics", home: MyApp1(), )); }
用MaterialApp启动
1. class MaterialApp extends StatefulWidget { 2. *** 3. }