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

Flutter WebView返回按钮问题:模拟器按返回键直接退出如何修复?

Flutter WebView 返回键不回退直接退出的修复方案

你的问题根源在于PopScope的配置错误:canPop: true会让Flutter优先执行默认的返回逻辑(直接退出应用),导致你写的WebView回退代码根本没机会生效。

修改PopScope部分的代码即可解决,具体调整如下:

  1. 将canPop设为false,禁用系统默认返回行为
  2. 在onPopInvoked中完善逻辑:先判断WebView能否回退,能则让WebView返回,不能再退出应用

修改后的完整代码:

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

final uri = Uri.parse('https://google.com');

class HomeScreen extends StatelessWidget {
  WebViewController controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setNavigationDelegate(NavigationDelegate(
      onPageFinished: (String url){
        print(url);
      }
    ))
    ..loadRequest(uri);

  HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
   return PopScope(
      // 关键修改1:禁用系统默认返回行为
      canPop: false,
      onPopInvoked : (didPop) async {
          // 关键修改2:先判断WebView是否能回退
          if(await controller.canGoBack()){
            controller.goBack();
          } else {
            // WebView无法回退时,再退出应用
            Navigator.of(context).pop();
          }
        },
    child : Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.orange,
        title: Text('Code Factory'),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              controller.loadRequest(uri);
            },
            icon: Icon(Icons.home),
          ),
        ],
      ),
      body: WebViewWidget(controller: controller),
    ),
    );
  }
}

这样修改后,按下返回键时会先检查WebView是否有历史页面:有则返回上一页,没有则退出应用,符合预期逻辑。

内容的提问来源于stack exchange,提问作者gill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:07:40