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

Flutter WebView按返回键关闭应用及_onWillPop方法报错问题

问题分析

报错的原因是你没有定义_onWillPop方法,系统找不到该方法所以抛出错误。要实现按下返回键回到WebView上一页而非关闭应用的功能,按以下步骤修改代码即可:

解决步骤
  1. 声明WebViewController实例
    在你的State类中添加变量,用来控制WebView的导航行为:
WebViewController? _webViewController;
  1. 绑定控制器到WebView
    在WebView组件中添加onWebViewCreated回调,将创建好的控制器赋值给我们声明的变量:
WebView(
  javascriptMode: JavascriptMode.unrestricted,
  initialUrl: 'https://google.com',
  onWebViewCreated: (controller) {
    _webViewController = controller;
  },
  // 保留你原本的navigationDelegate、onPageFinished等代码
)
  1. 实现_onWillPop方法
    在State类中添加该方法,判断WebView是否能返回上一页,能则执行返回操作,否则允许应用退出:
Future<bool> _onWillPop(BuildContext context) async {
  if (_webViewController != null && await _webViewController!.canGoBack()) {
    _webViewController!.goBack();
    return false; // 阻止应用退出
  } else {
    return true; // 允许应用退出
  }
}
  1. 修正WillPopScope的回调参数
    把原来的onWillPop: () => onWillPop(context)改为调用我们定义的方法:
WillPopScope(
  onWillPop: () => _onWillPop(context),
  child: WebView(/* 你的WebView代码 */),
)
完整修正后的代码片段
WebViewController? _webViewController;
bool isLoading = false;

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: Stack(
        children: <Widget>[
          WillPopScope(
            onWillPop: () => _onWillPop(context),
            child: WebView(
              javascriptMode: JavascriptMode.unrestricted,
              initialUrl: 'https://google.com',
              onWebViewCreated: (controller) {
                _webViewController = controller;
              },
              navigationDelegate: (NavigationRequest request) {
                setState(() {
                  isLoading = true;
                });
                return NavigationDecision.navigate;
              },
              onPageFinished: (String url) {
                setState(() {
                  isLoading = false;
                });
              },
            ),
          ),
          isLoading
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : const SizedBox.shrink(),
        ],
      ),
    ),
  );
}

Future<bool> _onWillPop(BuildContext context) async {
  if (_webViewController != null && await _webViewController!.canGoBack()) {
    _webViewController!.goBack();
    return false;
  } else {
    return true;
  }
}

注:将原代码中的Stack()替换为SizedBox.shrink(),更简洁且不影响布局效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:50:26