蓝色天空网mbsky.com · 知识 · 实践 · 创造Flutter · 本地阅读预览
教程 / 移动开发 / Flutter

Flutter 导航与路由

系统掌握 Flutter Navigator 栈式页面导航、MaterialPageRoute/CupertinoPageRoute/PageRouteBuilder 过渡差异、构造传参与命名路由、onGenerateRoute 动态解析与路由选型。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Navigator 路由栈与跨平台页面过渡

Flutter 的 `Navigator` 采用后进先出(LIFO)的栈(Stack)结构管理页面路由:调用 `push` 将新页面压入栈顶;调用 `pop()` 弹出当前页(可传入返回值给上一页 `await` 接收);登录跳转首页等不可回退场景使用 `pushReplacement` 替换栈顶路由;一键退回根页面可使用 `popUntil((route) => route.isFirst)`。本站离线路由栈验证器实测了上述全部 4 种栈操作的精确路径快照与返回值传递。

页面切换动画由具体 `Route` 实现决定:`MaterialPageRoute` 呈现 Android/Material 风格过渡,`CupertinoPageRoute` 呈现 iOS 风格的右侧滑入与边缘左滑返回手势;若需要自定义淡入淡出、缩放等特效,可使用 `PageRouteBuilder` 配置 `pageBuilder`、`transitionsBuilder`(如 `FadeTransition`)及 `transitionDuration`。

页面传参、命名路由与 onGenerateRoute 动态分发

页面间传值最直接、类型最安全的方式是通过目标页构造函数传入 `final` 参数(如 `ProductDetailPage(productId: 123)`)。当页面数量较多时,可在 `MaterialApp` 中配置 `initialRoute` 与静态 `routes` 映射表,通过 `Navigator.pushNamed(context, '/user', arguments: {...})` 跳转,并在目标页借助 `ModalRoute.of(context)?.settings.arguments` 提取参数。

当需要按路径动态解析参数、校验权限或兜底 404 页面时,应使用 `MaterialApp.onGenerateRoute` 回调:根据 `settings.name` 与 `settings.arguments` 构造对应 `MaterialPageRoute`,对未匹配路径统一返回 `NotFoundPage`。需特别注意:处理形如 `/product/sku_99` 的动态路径时,应使用 `Uri.parse` 或前缀匹配(如 `startsWith('/product/')`)切分尾段 ID,而不能用精确相等的 `case '/product':` 匹配。简单应用用基础 `Navigator` 即可,中大型涉及深链与 Web URL 同步的项目建议进一步采用声明式路由库(如官方维护的 `go_router`)。

运行 Navigator 栈操作、跨平台过渡规格、参数传递与 onGenerateRoute 动态分发离线核验

python · 阅读源码
"""Offline Flutter Navigator 1.0 stack, route transitions, argument passing, named routes & onGenerateRoute verifier for Ch13 (navigation)."""
import json

VERSION = "CPython 3.12.14 offline Flutter/Dart architecture & runtime verifier (Flutter SDK absent)"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


class NavigatorStack:
    def __init__(self, initial_route="/"):
        self.stack = [{"name": initial_route, "args": None, "transition": "root"}]
        self.last_pop_result = None

    def push(self, name, args=None, transition="MaterialPageRoute"):
        self.stack.append({"name": name, "args": args, "transition": transition})

    def pop(self, result=None):
        if len(self.stack) > 1:
            self.last_pop_result = result
            return self.stack.pop()
        return None

    def push_replacement(self, name, args=None, transition="MaterialPageRoute"):
        self.stack[-1] = {"name": name, "args": args, "transition": transition}

    def pop_until_first(self):
        while len(self.stack) > 1:
            self.stack.pop()


def on_generate_route(name, arguments=None):
    if name == "/":
        return {"page": "HomePage", "params": {}}
    if name == "/detail":
        args = arguments or {}
        return {"page": "DetailPage", "params": {"id": args.get("id", 0), "title": args.get("title", "")}}
    if name.startswith("/product/"):
        product_id = name.split("/")[-1]
        return {"page": "ProductPage", "params": {"id": product_id}}
    return {"page": "NotFoundPage", "params": {"requested": name}}


def main():
    cases = []

    # Case 1: Navigator push, pop(result), pushReplacement, popUntil(isFirst)
    nav = NavigatorStack("/")
    nav.push("/detail")
    nav.push("/editor")
    nav.pop("返回的数据")
    after_pop = ([r["name"] for r in nav.stack], nav.last_pop_result)
    nav.push_replacement("/home_v2")
    after_replace = [r["name"] for r in nav.stack]
    nav.push("/step2")
    nav.pop_until_first()
    after_pop_until = [r["name"] for r in nav.stack]
    cases.append(
        check(
            "navigator_stack_operations",
            "Verify LIFO Navigator stack push, pop with return value, pushReplacement, and popUntil(isFirst)",
            {
                "after_pop_stack": ["/", "/detail"],
                "pop_result": "返回的数据",
                "after_replace": ["/", "/home_v2"],
                "after_pop_until": ["/"],
            },
            {
                "after_pop_stack": after_pop[0],
                "pop_result": after_pop[1],
                "after_replace": after_replace,
                "after_pop_until": after_pop_until,
            },
        )
    )

    # Case 2: MaterialPageRoute vs CupertinoPageRoute vs PageRouteBuilder metadata
    routes = {
        "android": {"route": "MaterialPageRoute", "animation": "bottom_up_fade", "duration_ms": 300},
        "ios": {"route": "CupertinoPageRoute", "animation": "right_to_left_slide", "swipe_back": True},
        "custom": {"route": "PageRouteBuilder", "transition": "FadeTransition", "duration_ms": 300},
    }
    cases.append(
        check(
            "platform_route_transitions",
            "Verify MaterialPageRoute, CupertinoPageRoute, and custom PageRouteBuilder FadeTransition(300ms) specs",
            {"android_anim": "bottom_up_fade", "ios_swipe_back": True, "custom_duration_ms": 300},
            {
                "android_anim": routes["android"]["animation"],
                "ios_swipe_back": routes["ios"]["swipe_back"],
                "custom_duration_ms": routes["custom"]["duration_ms"],
            },
        )
    )

    # Case 3: Constructor argument passing & Named Route arguments extraction
    nav2 = NavigatorStack("/")
    nav2.push("/product_detail", args={"productId": 123})
    nav2.push("/user", args={"name": "张三", "age": 25})
    top_args = nav2.stack[-1]["args"]
    cases.append(
        check(
            "route_arguments_and_named_table",
            "Verify typed constructor arguments (productId=123) and ModalRoute.of(context).settings.arguments map extraction",
            {"product_id": 123, "user_name": "张三", "user_age": 25, "depth": 3},
            {
                "product_id": nav2.stack[1]["args"]["productId"],
                "user_name": top_args["name"],
                "user_age": top_args["age"],
                "depth": len(nav2.stack),
            },
        )
    )

    # Case 4: onGenerateRoute dynamic path & fallback 404 resolution
    r_detail = on_generate_route("/detail", {"id": 42, "title": "Flutter 路由"})
    r_product = on_generate_route("/product/sku_99")
    r_404 = on_generate_route("/unknown/path")
    cases.append(
        check(
            "on_generate_route_dispatch",
            "Verify onGenerateRoute handles arguments, dynamic /product/:id path parsing, and NotFoundPage fallback",
            {
                "detail": {"page": "DetailPage", "params": {"id": 42, "title": "Flutter 路由"}},
                "product": {"page": "ProductPage", "params": {"id": "sku_99"}},
                "fallback": "NotFoundPage",
            },
            {"detail": r_detail, "product": r_product, "fallback": r_404["page"]},
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 push/pop(返回值)/pushReplacement/popUntil 栈演变、三类路由过渡规格、构造与命名参数提取及 /product/:id 与 404 兜底。
运行 Navigator 栈操作、跨平台过渡规格、参数传递与 onGenerateRoute 动态分发离线核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:a12880f1d6a972d4f57260301acfdc09c1456398605cbf6e559bb49681aacb86

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Flutter 导航与路由实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:952f714fe95f527e46db5a4a0d4b85d6a2fb957d663b658bc7c471eb180e0e59

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在登录成功后跳转至首页时,为什么通常使用 `Navigator.pushReplacement` 而不是 `Navigator.push`?

展开参考解答

`pushReplacement` 会用首页替换栈中的登录页,避免用户在首页点击系统返回键时意外退回登录界面。

规范与官方依据