Flutter提示之Navigator operation requested with a context that does not include a Navigator.
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的继承关系
class Navigator extends StatefulWidget {
}
但是我的代码是这样的
class MyApp1 extends StatelessWidget {
}
我们需要使用StatefulWidget的Context
4、解决办法
void main() {
runApp(MaterialApp(
title: "Navigation basics",
home: MyApp1(),
));
}
用MaterialApp启动
class MaterialApp extends StatefulWidget {
***
}
赞 (0)