Flutter WebView按返回键关闭应用及_onWillPop方法报错问题
问题分析
报错的原因是你没有定义_onWillPop方法,系统找不到该方法所以抛出错误。要实现按下返回键回到WebView上一页而非关闭应用的功能,按以下步骤修改代码即可:
解决步骤
- 声明WebViewController实例
在你的State类中添加变量,用来控制WebView的导航行为:
WebViewController? _webViewController;
- 绑定控制器到WebView
在WebView组件中添加onWebViewCreated回调,将创建好的控制器赋值给我们声明的变量:
WebView( javascriptMode: JavascriptMode.unrestricted, initialUrl: 'https://google.com', onWebViewCreated: (controller) { _webViewController = controller; }, // 保留你原本的navigationDelegate、onPageFinished等代码 )
- 实现
_onWillPop方法
在State类中添加该方法,判断WebView是否能返回上一页,能则执行返回操作,否则允许应用退出:
Future<bool> _onWillPop(BuildContext context) async { if (_webViewController != null && await _webViewController!.canGoBack()) { _webViewController!.goBack(); return false; // 阻止应用退出 } else { return true; // 允许应用退出 } }
- 修正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
相关产品推荐
相关产品推荐

