navigation_channel.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import 'package:flutter/services.dart';
  2. import 'package:go_router/go_router.dart';
  3. /// 平台(iOS/Android)主动下发路由时,通过此 Channel 传递给 Flutter。
  4. ///
  5. /// navigateTo:用 [GoRouter.go] 清空整个导航栈后跳转到目标路由。
  6. /// 配合 Android 端追加的 _ts 时间戳,确保缓存引擎下每次打开 Flutter 页面都重建 State。
  7. ///
  8. /// iOS 侧调用方式:
  9. /// ```objc
  10. /// [engine.navigationChannel invokeMethod:@"pushRouteInformation"
  11. /// arguments:@{@"location": @"/expense/apply"}];
  12. /// ```
  13. ///
  14. /// 或者通过自定义 channel:
  15. /// ```objc
  16. /// FlutterMethodChannel *ch = [FlutterMethodChannel
  17. /// methodChannelWithName:@"com.tboss.oa/navigation"
  18. /// binaryMessenger:engine.binaryMessenger];
  19. /// [ch invokeMethod:@"navigateTo" arguments:@"/expense/apply"];
  20. /// ```
  21. class NavigationChannel {
  22. static const _channel = MethodChannel('com.tboss.oa/navigation');
  23. /// 开始监听平台下发的导航指令。
  24. ///
  25. /// [router] 必须是已初始化的 GoRouter 实例。
  26. static void startListening(GoRouter router) {
  27. _channel.setMethodCallHandler((call) async {
  28. switch (call.method) {
  29. case 'navigateTo':
  30. final route = call.arguments as String?;
  31. if (route != null && route.isNotEmpty) {
  32. router.go(route);
  33. }
  34. break;
  35. case 'pushRoute':
  36. final route = call.arguments as String?;
  37. if (route != null && route.isNotEmpty) {
  38. router.push(route);
  39. }
  40. break;
  41. default:
  42. break;
  43. }
  44. });
  45. }
  46. }