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");

复杂传参数 请看后续

相关推荐
Манго нектар29 分钟前
JavaScript for循环语句
开发语言·前端·javascript
helloxmg2 小时前
鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息
flutter
Zheng1132 小时前
【可视化大屏】将柱状图引入到html页面中
javascript·ajax·html
helloxmg2 小时前
鸿蒙harmonyos next flutter混合开发之开发package
flutter·华为·harmonyos
john_hjy2 小时前
【无标题】
javascript
软件开发技术深度爱好者3 小时前
用HTML5+CSS+JavaScript庆祝国庆
javascript·css·html5
汪子熙3 小时前
Angular 服务器端应用 ng-state tag 的作用介绍
前端·javascript·angular.js
昨天;明天。今天。9 小时前
案例-表白墙简单实现
前端·javascript·css
安冬的码畜日常9 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
小御姐@stella9 小时前
Vue 之组件插槽Slot用法(组件间通信一种方式)
前端·javascript·vue.js