Flutter GetX-路由中间件
Smoothness 2022/12/5 GetXGetX-middleware
本文介绍Getx
路由中间件的声明和使用。
# 定义
说明:优先级越低越先执行
- 重写
class MiddleWare1 extends GetMiddleware { // TODO: implement priority int? get priority => -1; //重定向,当正在搜索被调用路由的页面时,将调用该函数 RouteSettings? redirect(String? route) { print('redirect1----'); //return super.redirect(route); return const RouteSettings(name: AppRoutes.login); } //创建任何内容之前调用此函数 GetPage? onPageCalled(GetPage? page) { print('onPageCalled1----'); //return super.onPageCalled(page); //return page?.copy(name: AppRoutes.login); return GetPage(name: AppRoutes.login, page: () => LoginWidget()); } //这个函数将在绑定初始化之前被调用。在这里您可以更改此页面的绑定。 List<Bindings>? onBindingsStart(List<Bindings>? bindings) { print('onBindingsStart1----'); //return super.onBindingsStart(bindings); bindings?.add(LoginBinding()); return bindings; } //此函数将在绑定初始化后立即调用。在这里,您可以在创建绑定之后和创建页面小部件之前执行一些操作 GetPageBuilder? onPageBuildStart(GetPageBuilder? page) { print('onPageBuildStart1----'); //return super.onPageBuildStart(page); return page; } //该函数将在调用 GetPage.page 函数后立即调用,并为您提供函数的结果。并获取将显示的小部件 Widget onPageBuilt(Widget page) { print('onPageBuilt1 ----'); //return super.onPageBuilt(page); return page; } //此函数将在处理完页面的所有相关对象(控制器、视图等)后立即调用 void onPageDispose() { print('onPageDispose1 ----'); super.onPageDispose(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 示例
- 定义
- /lib/common/middleware/router_auth.dart
import 'package:flutter/material.dart'; import 'package:flutter_application_1/common/router/app_routes.dart'; import 'package:get/route_manager.dart'; class RouteAuthMiddleware extends GetMiddleware { int priority = 0; RouteAuthMiddleware({this.priority}); RouteSettings redirect(String route) { var isLogin = false; if (!isLogin) { Future.delayed( const Duration(seconds: 1), () => Get.snackbar("提示", "请先登录APP")); } return isLogin || route == AppRoutes.Login ? null : const RouteSettings(name: AppRoutes.Login); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- /lib/common/middleware/router_auth.dart
- 使用
- 路由配置
class AppPages { static const INITIAL = AppRoutes.Home; static final List<GetPage> routes = [ // ... GetPage(name: AppRoutes.My, page: () => const AccountPage(), middlewares: [ RouteAuthMiddleware(priority: 1) ]) // ... ]; static final unknownRoute = GetPage(name: AppRoutes.Notfound, page: () => const NotFoundView()); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- 路由配置