1 项目中添加最新的依赖
go_router: ^13.1.0
如下图所示,我当前使用的flutter版本为3.16.0
然后修改应用的入口函数如下:
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 就是配置的所有的路由页面,比如我这里的配置如下:
final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return MyHomePage(); }, routes: [ GoRoute( path: 'two', builder: (BuildContext context, GoRouterState state) { return TwoPage(); }, ), ], ), ], );
“/” 配置的就是加载的默认的启动的首页面,然后我这里面相当于是配置了两个基本的页面。
2 实现基本的页面交互
在页面MyHomePage放一个按钮,点击按钮打开 TwoPage 第二个页面,打开页面的核心代码如下:
使用 Navigator 正常操作如下“
Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { return TwoPage(); }));
使用 go_router 操作如下:
context.go("/two");
然后在页面 TwoPage 中点击按钮返回上一个页面:
使用 Navigator 正常操作如下:
Navigator.of(context).pop();
用 go_router 操作如下:
context.pop();
3 页面跳转传参数
基本简单参数传递,比如一个 userId,页面路由定义如下:ThreePage就是我定义的目标页面,它需要一个参数 userId。
GoRoute( path: 'three/:userId', builder: (BuildContext context, GoRouterState state) { // 使用 state.params 获取路由参数的值 final userId = (state.pathParameters['userId']!); return ThreePage(userId:userId); }, ),
点击一个按钮跳转目标页面,我这里传的参数 userId的值为 123
context.go("/three/123");
复杂传参数 请看后续
文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...