flutter简单路由管理

192 阅读2分钟

一、术语

路由(route)

  • 在 Flutter 中,屏 (screen) 和 页面 (page) 都叫做 路由 (route)。
  • 在 Android 开发中,Activity 相当于“路由”,在 iOS 开发中,ViewController 相当于“路由”。在 Flutter 中,“路由”也是一个 widget。

导航(Navigator):

  • Navigator是一个路由管理的组件,它提供了打开和退出路由页方法。[Navigator官方链接]
  • Navigator常用的路由管理方法包括pushpop

概述

  • 路由在移动开发中通常指页面,在Android中通常指代一个Activity。Flutter中的路由管理与原生开发较类似,路由管理指页面跳转关系。
  • 路由入栈(push)操作对应打开一个新页面,出栈(pop)操作对应关闭页面。

1、简单路由

  • 入栈,即新开一个页面,需要调用Future<T?> push<T extends Object?>(BuildContext context, Route<T> route)
  • 出栈,即关闭页面,需要调用pop<T extends Object?>(BuildContext context, [ T? result ])
  • Navigator:这是一个组件,用于管理和维护一个基于栈堆的历史记录,通过pushpop进行页面的跳转。

入栈

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => NewPage()),
);

出栈

Navigator.pop(context);

maybePop()

maybePop方法只会在路由堆栈有可弹路由时才会出栈。

Navigator.maybePop(context);

canPop()

canPop方法可以判断当前路由堆栈是否可以出栈。

if (Navigator.canPop(context)) {
    Navigator.pop(context);
}

pushReplacement()

pushReplacement方法可以用于切换路由页面。

Navigator.pushReplacement(
    context,
    MaterialPageRoute(builder: (context) => NewPage()),
);

pushAndRemoveUntil()

进入新页面并之前所有页面。

Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (BuildContext context) {
    return FourthPage();
}), (route) => false);

2、路由定义(命名路由)

在App中定义router:

routes: {
          '/': (context) => const HomePage(),
          '/second': (context) => const SecondScreen(),
        }

3、Navigator方法介绍

1.Navigator.push

  • push(BuildContext context, Route route)

将给定的路由入栈(即打开新的页面),返回值是一个Future对象,用以接收新路由出栈(即关闭)时的返回数据。

  • pushNamed(BuildContext context, String routeName, {Object? arguments,})

将给定的路由名入栈,返回值是一个Future对象,用以接收新路由出栈(即关闭)时的返回数据。

2.Navigor.pop

  • pop(BuildContext context, [ T? result ])

将栈顶路由出栈,result为页面关闭时返回给上一个页面的数据

3.其他

Navigator还有很多其他方法,如Navigator.replaceNavigator.popUntil等。