You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中WebView结合PopScope处理返回键出现黑屏问题求助

问题解决:WebView返回键逻辑修复及黑屏问题处理

问题根源

你的代码出现黑屏的核心原因:

  • SystemNavigator.pop()会直接尝试退出当前路由/应用,但WebView所在的Page3是嵌套在IndexedStack中的页面,并非独立路由,调用该方法会导致页面状态异常。
  • PopScope的canPop设为true时,系统会优先执行默认的pop行为,干扰自定义返回逻辑。

修复方案

修改WebView页面的PopScope配置,替换错误的退出逻辑为切换到底部导航首页:

@override
Widget build(BuildContext context) {
  return PopScope(
    // 设为false,禁止系统默认pop行为,完全自定义返回逻辑
    canPop: false,
    onPopInvokedWithResult: (didPop, result) async {
      if (await controller.canGoBack()) {
        // WebView可返回时,退回到上一网页
        await controller.goBack();
      } else {
        // WebView无法返回时,切换到底部导航首页(索引0)
        Get.find<BottomNavbarController>().updateIndex(0);
      }
    },
    child: Scaffold(
      backgroundColor: const Color(0xFF000000),
      body: Padding(
        padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).size.height * 0.01),
        child: SafeArea(
          child: WebViewWidget(
            controller: controller,
          ),
        ),
      ),
    ),
  );
}

关键说明

  1. canPop: false:阻止系统自动执行pop操作,确保自定义逻辑完全接管返回键行为。
  2. 切换首页逻辑:通过Get.find<BottomNavbarController>()获取底部导航控制器,调用updateIndex(0)直接切换到Page1,符合需求。
  3. 避免黑屏:不再使用SystemNavigator.pop(),而是通过修改底部导航索引切换页面,保持页面栈正常状态。

额外注意事项

确保BottomNavbarController已在全局或父组件中通过Get.put(BottomNavbarController())完成初始化,否则Get.find()会抛出异常。

内容的提问来源于stack exchange,提问作者I. Antonov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:32:19