my_router_history_manager.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import 'package:flutter/services.dart';
  2. class MyRouterHistoryManager {
  3. //如果页面只需要垂直方向,放入此白名单即可自动处理
  4. static const onlyVerticalOrientationRouterName = [
  5. "AUTH_LOGIN", //登录页面,保持垂直布局
  6. "SPLASH", //闪屏页面,保持垂直布局
  7. ];
  8. static final MyRouterHistoryManager _instance = MyRouterHistoryManager._internal();
  9. factory MyRouterHistoryManager() {
  10. return _instance;
  11. }
  12. MyRouterHistoryManager._internal();
  13. final List<String?> _routeNames = [];
  14. // 自己记录路由栈 - 存入
  15. void putRouterByName(String? routeName) {
  16. if (routeName != null) {
  17. _routeNames.add(routeName);
  18. try2SetVerticalOrientation(routeName);
  19. }
  20. }
  21. // 自己记录路由栈 - 移除
  22. void removeRouterByName(String? routeName) {
  23. if (routeName != null && _routeNames.contains(routeName)) {
  24. _routeNames.remove(routeName);
  25. try2RestoreOrientation(routeName);
  26. }
  27. }
  28. //尝试设置只竖屏方向展示页面
  29. void try2SetVerticalOrientation(String routeName) {
  30. if (onlyVerticalOrientationRouterName.contains(routeName)) {
  31. //如果包含白名单路由,需要设置垂直
  32. SystemChrome.setPreferredOrientations([
  33. DeviceOrientation.portraitUp,
  34. ]);
  35. }
  36. }
  37. //尝试设置横竖屏方向展示页面
  38. void try2RestoreOrientation(String routeName) {
  39. if (onlyVerticalOrientationRouterName.contains(routeName)) {
  40. //如果包含白名单路由,需要恢复全局
  41. SystemChrome.setPreferredOrientations([
  42. DeviceOrientation.portraitUp,
  43. DeviceOrientation.landscapeLeft,
  44. DeviceOrientation.landscapeRight,
  45. ]);
  46. }
  47. }
  48. //获取到全部的RouterName数组
  49. List<String?> get routeNames => _routeNames;
  50. //查询当前栈中是否存在指定的路由名称
  51. bool isRouteExist(String routeName) {
  52. return _routeNames.contains(routeName);
  53. }
  54. // 只是检查栈顶
  55. bool isTopRouteExist(String routeName) {
  56. if (_routeNames.isNotEmpty) {
  57. return _routeNames.last == routeName;
  58. } else {
  59. return false;
  60. }
  61. }
  62. }