flutter go_router 官方路由(一)基本使用

1 项目中添加最新的依赖
dart 复制代码
go_router: ^13.1.0

如下图所示,我当前使用的flutter版本为3.16.0

然后修改应用的入口函数如下:

dart 复制代码
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

void main() {
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
    );
    // return MaterialApp(
    //   title: 'Flutter Demo',
    //   theme: ThemeData(
    //     colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
    //     useMaterial3: true,
    //   ),
    //   home:  MyHomePage(),
    // );
  }
}

其实就是将原来的入口 MaterialApp 使用 MaterialApp.router 替换了,参数 routerConfig 就是配置的所有的路由页面,比如我这里的配置如下:

dart 复制代码
final GoRouter _router = GoRouter(
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return MyHomePage();
      },
      routes: <RouteBase>[
        GoRoute(
          path: 'two',
          builder: (BuildContext context, GoRouterState state) {
            return TwoPage();
          },
        ),
      ],
    ),
  ],
);

"/" 配置的就是加载的默认的启动的首页面,然后我这里面相当于是配置了两个基本的页面。

2 实现基本的页面交互

在页面MyHomePage放一个按钮,点击按钮打开 TwoPage 第二个页面,打开页面的核心代码如下:

使用 Navigator 正常操作如下"

dart 复制代码
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (BuildContext context) {
      return TwoPage();
    }));

使用 go_router 操作如下:

dart 复制代码
context.go("/two");

然后在页面 TwoPage 中点击按钮返回上一个页面​:

使用 Navigator 正常操作如下:

dart 复制代码
 Navigator.of(context).pop();

​用 go_router 操作如下:

dart 复制代码
context.pop();
3 页面跳转传参数

基本简单参数传递,比如一个 userId,页面路由定义如下:ThreePage就是我定义的目标页面,它需要一个参数 userId。

dart 复制代码
GoRoute(
    path: 'three/:userId',
    builder: (BuildContext context, GoRouterState state) {
      // 使用 state.params 获取路由参数的值
      final userId = (state.pathParameters['userId']!);
      return ThreePage(userId:userId);
    },
  ),

点击一个按钮跳转目标页面,我这里传的参数 userId的值为 123

dart 复制代码
context.go("/three/123");

复杂传参数 请看后续

相关推荐
kyriewen5 小时前
豆包和千问同时关了智能体,我用它们搭的 3 个自动化全废了——迁移方案整理
前端·javascript·ai编程
铁皮饭盒6 小时前
用 Bun.cron 定时 7 月 7 日,为啥? 看图1
javascript
GitLqr6 小时前
Flutter 3.44 插件内置 Kotlin (KGP) 双向兼容适配指南
android·flutter·dart
之歆7 小时前
Vue商品详情与放大镜组件
前端·javascript·vue.js
丹宇码农12 小时前
把 HLS 字幕玩出花:zwPlayer 如何让 M3U8 视频支持全文搜索、翻译与码率自适应
前端·javascript·音视频·hls·视频播放器
GuWenyue13 小时前
提示词彻底过时?一套上下文工程方案,3步让LLM落地生产,代码直接复用
前端·javascript·人工智能
用户9385156350713 小时前
深入理解 JavaScript 中的 this 与数据存储的奥秘
前端·javascript
Tian_Hang13 小时前
eclipse ditto 学习笔记
运维·服务器·开发语言·javascript·3d
想你依然心痛16 小时前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
竹林81816 小时前
用 Pinata + IPFS 存 NFT 元数据踩了三天坑,我总结了这份完整的前端实现方案
javascript