diff --git a/lib/features/my/presentation/web_view/user_info_pages.dart b/lib/features/my/presentation/web_view/user_info_pages.dart index 167c49b6..45599407 100644 --- a/lib/features/my/presentation/web_view/user_info_pages.dart +++ b/lib/features/my/presentation/web_view/user_info_pages.dart @@ -178,6 +178,7 @@ class _UserInfoCardState extends State { } // 扫码绑定设备逻辑(保留) +// 扫码绑定设备逻辑(修复版) Future _handleScanAndBind(BuildContext context) async { bool isScanned = false; @@ -203,7 +204,6 @@ class _UserInfoCardState extends State { final String? code = barcodes.first.rawValue; if (code != null && code.isNotEmpty) { isScanned = true; - // 使用 addPostFrameCallback 确保在帧渲染后执行,避免锁死 WidgetsBinding.instance.addPostFrameCallback((_) { if (context.mounted && Navigator.canPop(context)) { Navigator.pop(context, code); @@ -256,32 +256,38 @@ class _UserInfoCardState extends State { return; } - // 3. 显示加载框 - // 保存 BuildContext 引用,防止后续 context 变化导致找不到正确的 Navigator + // 3. 显示加载框:保存加载弹窗的 BuildContext + BuildContext? loadingContext; // 新增:保存加载弹窗的上下文 showDialog( context: context, barrierDismissible: false, - builder: (loadingContext) => const Center(child: CircularProgressIndicator()), + builder: (context) { + loadingContext = context; // 保存这个 context + return const Center(child: CircularProgressIndicator()); + }, ); try { final devicesCubit = GetIt.I(); await devicesCubit.bindDevice(deviceCode, ''); - // ✅ 成功:安全关闭加载框 - if (context.mounted && Navigator.canPop(context)) { - Navigator.pop(context); + // ✅ 成功:用 loadingContext 关闭弹窗 + if (loadingContext != null && Navigator.canPop(loadingContext!)) { + Navigator.pop(loadingContext!); + } + + if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('设备绑定成功!'), backgroundColor: Colors.green), ); } } catch (e) { - // ✅ 失败:安全关闭加载框 (关键修复点) - // 即使发生了 Framework 错误,也要尝试关闭弹窗 - if (context.mounted && Navigator.canPop(context)) { - Navigator.pop(context); + // ❌ 失败:用 loadingContext 关闭弹窗 + if (loadingContext != null && Navigator.canPop(loadingContext!)) { + Navigator.pop(loadingContext!); + } - // 显示具体错误信息 + if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('绑定失败:${e.toString()}'), @@ -289,20 +295,6 @@ class _UserInfoCardState extends State { duration: const Duration(seconds: 4), ), ); - } else { - // 极端情况:如果 Navigator 已经锁死无法 pop,尝试用其他方式提示用户 - // 或者等待下一帧再试 - WidgetsBinding.instance.addPostFrameCallback((_) { - if (context.mounted) { - // 尝试再次关闭,或者只显示错误提示 - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('绑定失败:${e.toString()} (请手动返回)'), - backgroundColor: Colors.orange, - ), - ); - } - }); } debugPrint('设备绑定失败详情:$e'); }