Flutter-路由导航

53 阅读1分钟

Flutter-路由导航

路由管理主要用到两个类Router和Navigator
Navigator

Navigator:管理所有的Route的Widget,通过一个Stack来进行管理的

官方的说法也很清晰:A widget that manages a set of child widge's with a stack discipline.那么我们开发中需要手动去创建一个Navigator吗?

并不需要,我们开发中使用的MaterialApp、CupertinoApp、WidgetsApp它们默认是有插 入Navigator的所以,我们在需要的时候,只需要直接使用即可

常用方法:push、pop

Navigator.of(context).push(MaterialPageRoute(builder: (ctx){
  return MyPaintingsPage();
}
  Navigator.of(context).pop();
                                             
                                             
  ///传递参数
                                               Navigator.of(context).push(MaterialPageRoute(
                            builder: (ctx) {
                              return MyPaintingsPage();
                            })).then((value) {
                              print(value);
                        })

拦截返回按钮

方式1
AppBar(
          title: Text("我的画作"),
          leading: IconButton(
            onPressed: () {
              ///自己写返回代码
            },
            icon: Icon(Icons.arrow_back),
          ),
        ),
方式2
WillPopScope(
     onWillPop: (){
       ///当返回为TRUE时,自动返回,flutter 帮我们执行返回操作
       /// 当返回false时,自行写返回代码
       return Future.value(true);
     },
     child:Scaffold()
  )

命名路由跳转方式

///命名路由跳转方式
MaterialApp(
  debugShowCheckedModeBanner: false,
  // home:MJYMainPage(),
  routes: {
    "/": (ctx) => MJYHomePage(),
    "/paintings": (ctx) => MyPaintingsPage()
  },
  initialRoute: "/",
​
);
​
///使用
 Navigator.of(context).pushNamed("/paintings")
   
   
   ///如果需要传递参数
   Navigator.of(context).pushNamed(MyPaintingsPage.routerName,arguments:"a home message" )
   
   
   ///接收参数
   class MyPaintingsPage extends StatelessWidget{
  static const String routerName = "/paintings";
  @override
  Widget build(BuildContext context) {
    final message = ModalRoute.of(context)?.settings.arguments as String;
    print("message:$message");
   return Scaffold(
     appBar:buildMJYNavBar("我的画作",),
     body:const PaintingListView()
   );
  }
}
 ///MaterialApp中,不改变page需要接收参数的情况也能使用命名路由的方式进行跳转
///是一个钩子函数
onGenerateRoute: (settings){
        ///if(settings.name == "/details")
  if(settings.name == DetailsPage.routerName)
        return MaterialPageRoute(builder: (ctx){
          ///arguments取值
          return DetailsPage(settings.arguments);
        })
      },
​
​
///具体跳转的地方
 Navigator.of(context).pushNamed(DetailsPage.routerName,arguments:"a home message" )

需求跳转到一个不存在的页面,代码不要报错,反而取到指定的unKnown页面

 
 Navigator.of(context).pushNamed("/settings")
/// MaterialApp中另外一个钩子函数
      onUnknownRoute: ((settings) {
        return MaterialPageRoute(builder: (ctx){
          return MJYUnKnowPage();
        });
      }),