flutter路由跳转问题:
Navigator operation requested with a context that does not include a Navigator.
出现问题情况,直接
void main()=>runApp(MyApp());
MyApp 是一个可变StatefulWidget这种情况下,如上情况提示路由控制器需要一个context但是当前navigator并不包含,所以报错
解决方案
外层使用StatelessWidget ,将路由跳转功能封装到StatefulWidget中
正确方式
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {'/other':(BuildContext context)=>Other()},
home: HomePage());
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("route"),
),
floatingActionButton: FloatingActionButton(onPressed: (){
Navigator.pushNamed(context, '/other');
}),
);
}
}
class Other extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text("other"),),);
}
}
上边代码运行正常
错误方式
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {'/other':(BuildContext context)=>Other()},
home: Scaffold(
appBar: AppBar(
title: Text('nav'),
),
floatingActionButton: FloatingActionButton(onPressed: (){
Navigator.pushNamed(context, '/other');
}),
),
);
}
}
class Other extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Other'),
),
body: Center(child: Text('other'),),
);
}
}
上面代码运行直接报异常,效果入下图