使用flutter的Navigator.push跳转页面
The context used to push or pop routes from the Navigator must be that of a widget that is a descend
我们先看这段代码:
void main() {
WidgetsFlutterBinding.ensureInitialized(); // 确定初始化
SystemChrome.setPreferredOrientations(// 使设备横屏显示
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
SystemChrome.setEnabledSystemUIOverlays([]); // 全屏显示
runApp(RouterTestRoute());
}
class NewRoute extends StatelessWidget{
NewRoute({
Key? key,
required this.text,
}):super(key:key);
final String text;
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp (
home:Scaffold(
appBar:AppBar(
title:Text('New Route'),
),
body:Center(
child:Column(
children: [
Text(text,textDirection:TextDirection.ltr),
RaisedButton(
onPressed: ()=>Navigator.pop(context,"back data"),
child: Text('back'),
)
],
)
),
)
);
}
}
class RouterTestRoute extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home:
Center(
child: RaisedButton(
child: Text('click'),
onPressed: () async{
var result = await Navigator.push(context,MaterialPageRoute( builder: (BuildContext context) {
return new NewRoute(text:'传入1');
}
),
);
print("路由返回值: "+result);
},
),
)
);
}
}
我们在使用flutter页面跳转api的时候会遇到The context used to push or pop routes from the Navigator must be that of a widget that is a descend这样的错误描述,意思是使用的Context必须是Navigator Widget的子类,
使用Navigator.push(context,MaterialPageRoute( builder: (BuildContext context)的时候我们要是有MaterialApp的上下文,但是当前context是StatelessWidget的实现类的上下文,所有我们需要拿到MaterialApp上context,
这个是修改后的代码:
void main() {
WidgetsFlutterBinding.ensureInitialized(); // 确定初始化
SystemChrome.setPreferredOrientations(// 使设备横屏显示
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
SystemChrome.setEnabledSystemUIOverlays([]); // 全屏显示
//下面是修改后的代码
runApp( MaterialApp(home:RouterTestRoute()));
}
class NewRoute extends StatelessWidget{
NewRoute({
Key? key,
required this.text,
}):super(key:key);
final String text;
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp (
home:Scaffold(
appBar:AppBar(
title:Text('New Route'),
),
body:Center(
child:Column(
children: [
Text(text,textDirection:TextDirection.ltr),
RaisedButton(
onPressed: ()=>Navigator.pop(context,"back data"),
child: Text('back'),
)
],
)
),
)
);
}
}
class RouterTestRoute extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
//下面是修改后的代码 返回一个Scaffold
return new Scaffold(
body:Center(
child: RaisedButton(
child: Text('click'),
onPressed: () async{
var result = await Navigator.push(context,MaterialPageRoute( builder: (BuildContext context) {
return new NewRoute(text:'传入1');
}
),
);
print("路由返回值: "+result);
},
),
)
);
}
}
具体context可以参考这个:深入理解BuildContext