Flutter WebView中如何实现点击设备返回键返回网页上一级页面
实现方案
核心逻辑是通过WillPopScope拦截系统返回事件,优先判断WebView是否存在可返回的历史浏览记录,存在则返回网页上一级,不存在再执行系统默认的返回逻辑。
完整修改后的代码如下:
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override MyAppState createState() => MyAppState(); } class MyAppState extends State<MyApp> { // 存储WebViewController实例 late WebViewController _webViewController; @override void initState() { super.initState(); if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView(); } @override Widget build(BuildContext context) { return MaterialApp( title: "Mobile App", // 拦截系统返回事件 home: WillPopScope( onWillPop: () async { // 判断WebView是否有可返回的历史记录 if (await _webViewController.canGoBack()) { // 返回WebView上一级页面 _webViewController.goBack(); // 阻止系统默认返回行为 return false; } // 无历史记录时执行系统默认返回逻辑 return true; }, child: Scaffold( body: SafeArea( child: WebView( initialUrl: 'https://flutter.dev', javascriptMode: JavascriptMode.unrestricted, // WebView初始化完成后获取控制器实例 onWebViewCreated: (controller) { _webViewController = controller; }, ) ) ), ), debugShowCheckedModeBanner: false, ); } }
修改说明
- 新增
_webViewController私有变量,用于存储WebView的控制器实例,后续所有网页相关操作(前进、后退、刷新等)都可以通过这个实例完成 - 给WebView添加
onWebViewCreated回调,在WebView初始化完成后拿到控制器实例赋值给我们定义的变量 - 在Scaffold外层包裹
WillPopScope组件,通过onWillPop回调拦截系统返回事件,优先处理WebView的页面回退逻辑
该逻辑同时兼容Android实体返回键、iOS手势返回的场景,不需要额外做平台适配。
内容的提问来源于stack exchange,提问作者Archangel
相关产品推荐
相关产品推荐

