阅读背景:

Flutter 返回按钮的监听

来源:互联网 
物理按钮和返回按钮的监听

Flutter 返回按钮的监听是通过 WillPopScope来实现的

class BackDemoState extends State<BackDemoWidget> { @override Widget build(BuildContext context) { return WillPopScope( onWillPop: _onWillPop, child: Scaffold( appBar: AppBar( title: const Text("返回键监听"), leading: IconButton( icon: const Icon(Icons.arrow_back), onPressed: (){ SmartDialog.showToast("返回"); if (Navigator.canPop(context)) { Navigator.pop(context); } else { SystemNavigator.pop(); } }, ), ), )); } Future<bool> _onWillPop() { SmartDialog.showToast("返回"); if (Navigator.canPop(context)) { Navigator.pop(context); } else { SystemNavigator.pop(); } return Future.value(false); } } WebView的返回监听 @override Widget build(BuildContext context) { return FutureBuilder<WebViewController>( future: _controller.future, builder: (context, snapshot) { return WillPopScope( onWillPop: () async { if (snapshot.hasData) { final bool canGoBack = await snapshot.data!.canGoBack(); if (canGoBack) { // 网页可以返回时,优先返回上一页 await snapshot.data!.goBack(); return Future.value(false); } } return Future.value(true); }, child: Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Stack( children: [ WebView( initialUrl: "https://www.baidu.com", javascriptMode: JavascriptMode.unrestricted, allowsInlineMediaPlayback: true, onWebViewCreated: (WebViewController webViewController) { _controller.complete(webViewController); }, onProgress: (int progress) { debugPrint('WebView is loading (progress : $progress%)'); setState(() { _progressValue = progress; }); }, ), if (_progressValue != 100) LinearProgressIndicator( value: _progressValue / 100, backgroundColor: Colors.transparent, minHeight: 2, ) else Gaps.empty, ], ), ), ); } ); }



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: