Flutter WillPopScope攔截返回事件原理示例詳解
一、 WillPopScope用法
WillPopScope本質是一個widget用于攔截物理按鍵返回事件(Android的物理返回鍵和iOS的側滑返回),我們先了解一下這個類, 很簡單,共有兩個參數(shù),子widget child和用于監(jiān)聽攔截返回事件的onWillPop方法
const WillPopScope({
super.key,
required this.child,
required this.onWillPop,
}) : assert(child != null);
下面我們以Android為例看一下用法,用法很簡單
body: WillPopScope(
child: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Text("back")
),
onWillPop: () async {
log("onWillPop");
/**返回 true 和不實現(xiàn)onWillPop一樣,自動返回,
*返回 false route不再響應物理返回事件,攔截返回事件自行處理
*/
return false;
},
),
在需要攔截返回事件的頁面添加WillPopScope后,返回值為false時,點擊物理返回鍵頁面沒有任何反應,需要自己實現(xiàn)返回邏輯。
二、使用WillPopScope遇到的問題
當flutter項目中只有一個Navigator時,使用上面的方式是沒有問題的,但是一個項目中往往有多個Navigator,我們就會遇到WillPopScope失效的情況(具體原理后面會解釋),先來看一個嵌套示例
主頁面main page, 由于MaterialApp就是一個Navigator, 所以我們在里面嵌套一個Navigator,示例只寫關鍵代碼
main page
body: WillPopScope(
child: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Navigator(
onGenerateRoute: (RouteSettings settings) => MaterialPageRoute(builder: (context) {
return FirstPage();
}),
)
),
onWillPop: () async {
print("onWillPop");
/**返回 true 和不實現(xiàn)onWillPop一樣,自動返回,
*返回 false route不再響應物理返回事件,攔截返回事件自行處理
*/
return true;
},
first page, 嵌入到主頁,創(chuàng)建路由可以跳轉第二頁
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Center(
child: InkWell(
child: const Text("第一頁"),
onTap: () {
//跳轉到第二頁
Navigator.push(context, MaterialPageRoute(builder: (context) {
return SecondPage();
}));
},
)),
onWillPop: () async {
//監(jiān)聽物理返回事件并打印
print("first page onWillScope");
return false;
});
}
}
第二頁
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async{
//監(jiān)聽物理返回事件并打印
print("second page onWillPop");
return false;
},
child: const Center(
child: Text("第二頁"),
),
);
}
}
運行后會發(fā)現(xiàn),點擊返回鍵只有主頁的onWillPop 監(jiān)聽到了物理返回事件,第一頁和第二頁的onWillPop沒有任何反應
I/flutter: onWillPop
看上去只響應了最初的Navigator,嵌套后的Navigator的監(jiān)聽沒有任何效果,為什么會出現(xiàn)這樣的問題呢?下面是對WillPopScope原理的講解,如果只想看解決辦法請直接跳到文章最后。
三、 WillPopScope原理
我們先看WillPopScope的源碼,WillPopScope的主要源碼就是下面兩段,很容易理解,就是在UI或者數(shù)據(jù)更新后,對比onWillPop有沒有變化并更新。
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (widget.onWillPop != null) {
_route?.removeScopedWillPopCallback(widget.onWillPop!);
}
//獲取ModalRoute
_route = ModalRoute.of(context);
if (widget.onWillPop != null) {
_route?.addScopedWillPopCallback(widget.onWillPop!);
}
}
@override
void didUpdateWidget(WillPopScope oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.onWillPop != oldWidget.onWillPop && _route != null) {
if (oldWidget.onWillPop != null) {
_route!.removeScopedWillPopCallback(oldWidget.onWillPop!);
}
if (widget.onWillPop != null) {
_route!.addScopedWillPopCallback(widget.onWillPop!);
}
}
}
重點看這一段,獲取ModalRoute并將onWillPop注冊到ModalRoute中
_route = ModalRoute.of(context);
if (widget.onWillPop != null) {
//該方法就是將onWillScope放到route持有的_willPopCallbacks數(shù)組中
_route?.addScopedWillPopCallback(widget.onWillPop!);
}
進入到ModalRoute中,看到注冊到_willPopCallbacks中的onWillPop在WillPop中被調用,注意看當 onWillPop返回值為false時,WillPop的返回值為RoutePopDisposition.doNotPop。
這里解決了一個小疑點,onWillPop返回值的作用,返回false就不pop。但是還沒有解決我們的主要疑問,只能接著往下看。
@override
Future<RoutePopDisposition> willPop() async {
final _ModalScopeState<T>? scope = _scopeKey.currentState;
assert(scope != null);
for (final WillPopCallback callback in List<WillPopCallback>.of(_willPopCallbacks)) {
if (await callback() != true) {
//當返回值為false時,doNotPop
return RoutePopDisposition.doNotPop;
}
}
return super.willPop();
}
接著找到調用WillPop的方法,是一個MaybePop的方法,這個方法里包含了同一個 Navigator里面頁面的彈出邏輯,這里我們不做分析,感興趣的可以自己研究。但是如果涉及到不同的Navigator呢?我們先看這個方法里面的返回值,這個很重要。但我們的問題同樣不是在這里能解答的,只能繼續(xù)向上追溯。
@optionalTypeArgs
Future<bool> maybePop<T extends Object?>([ T? result ]) async {
final _RouteEntry? lastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (lastEntry == null) {
return false;
}
assert(lastEntry.route._navigator == this);
final RoutePopDisposition disposition = await lastEntry.route.willPop(); // this is asynchronous
assert(disposition != null);
if (!mounted) {
// Forget about this pop, we were disposed in the meantime.
return true;
}
final _RouteEntry? newLastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (lastEntry != newLastEntry) {
// Forget about this pop, something happened to our history in the meantime.
return true;
}
switch (disposition) {
case RoutePopDisposition.bubble:
return false;
case RoutePopDisposition.pop:
pop(result);
return true;
case RoutePopDisposition.doNotPop:
return true;
}
}
那又是誰調用了maybePop方法呢, 那就是didPopRoute, didPopRoute方法位于_WidgetsAppState 中
@override
Future<bool> didPopRoute() async {
assert(mounted);
// The back button dispatcher should handle the pop route if we use a
// router.
if (_usesRouterWithDelegates) {
return false;
}
final NavigatorState? navigator = _navigator?.currentState;
if (navigator == null) {
return false;
}
return navigator.maybePop();
}
根據(jù)層層的追溯,我們現(xiàn)在來到下面的方法,這個方法很好理解,也是讓我很疑惑的地方。for循環(huán)遍歷_observes數(shù)組中的所有WidgetsBindingObserver。但是——注意這個轉折 如果數(shù)組中的第一個元素的didPopRoute方法返回true,那么遍歷結束,如果返回false那么最終會調用SystemNavigator.pop(),這個方法的意思是直接退出應用。也就是說handlePopRoute這個方法要么執(zhí)行數(shù)組里的第一個WidgetBindingObserver的didPopRoute要么退出應用。感覺這個for循環(huán)然并卵。
那為什么要講這個方法呢,因為應用監(jiān)聽到物理返回按鍵事件后會調用這個方法。
@protected
Future<void> handlePopRoute() async {
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
if (await observer.didPopRoute()) {
return;
}
}
SystemNavigator.pop();
}
現(xiàn)在我們知道了,應用監(jiān)聽到物理返回按鍵事件后會調用handlePopRoute方法。但是handlePopRoute中要么調用_observers數(shù)組的第一個item的didPopRoute方法,要么就退出應用。也就是說想要監(jiān)聽系統(tǒng)的返回事件要有一個注冊到_observers的WidgetBindingObserver并且還要是_observers數(shù)組里的第一個元素。通過搜索_observers的相關操作方法可以知道_observers添加元素只用到了add方法,所以第一個元素永遠不會變。那誰是第一個WidgetBindingObserver呢?那就是上文提到的_WidgetsAppState, 而_WidgetsAppState會持有一個NavigatorKey,這個NavigatorKey 就是應用最初Navigator的持有者。
綜上,我們了解了應用的物理返回鍵監(jiān)聽邏輯,永遠只會調用到應用的第一個Navigator,所以我們所有的監(jiān)聽返回邏輯只能用系統(tǒng)的第一個Navigator里面實現(xiàn)。那對于嵌套的Navigator我們該怎么辦呢?
四、嵌套Navigator無法監(jiān)聽物理返回按鍵的解決辦法
既然不能直接處理嵌套Navigator的物理返回事件,那就只能曲線救國了。 首先去掉無效的WillPopScope。
first page
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: InkWell(
child: const Text("第一頁"),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return SecondPage();
}));
},
));
}
}
second page
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Center(
child: Text("Second page"),
);
}
}
重頭戲來到了main page里面, 還是將onWillPop設置為false。攔截所有的物理返回事件。只需要給Navigator設置一個GlobalKey,然后在onWillPop中實現(xiàn)對應navigator的返回邏輯。
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
GlobalKey<NavigatorState> _key = GlobalKey();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: WillPopScope(
child: Center(
child: Navigator(
key: _key,
onGenerateRoute: (RouteSettings settings) => MaterialPageRoute(builder: (context) {
return FirstPage();
}),
)
),
onWillPop: () async {
print("onWillPop");
if(_key.currentState != null && _key.currentState!.canPop()) {
_key.currentState?.pop();
}
/**返回 true 和不實現(xiàn)onWillPop一樣,自動返回,
*返回 false route不再響應物理返回事件,攔截返回事件自行處理
*/
return false;
},
),
);
}
}
以上就是Flutter WillPopScope攔截返回事件原理示例詳解的詳細內容,更多關于Flutter WillPopScope攔截返回的資料請關注腳本之家其它相關文章!
相關文章
android中創(chuàng)建通知欄Notification代碼實例
這篇文章主要介紹了android中創(chuàng)建通知欄Notification代碼實例,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-05-05
android輕松管理安卓應用中的log日志 發(fā)布應用時log日志全部去掉的方法
android合理的管理log日志,在開發(fā)的時候打印出來,在發(fā)布的時候,把所有的log日志全部關掉,下面就把方法給你一一道來2013-11-11
Android12四大組件之Activity生命周期變化詳解
雖然說我們天天都在使用Activity,但是你真的對Activity的生命機制完全了解了嗎?Activity的生命周期方法只有七個,但是其實那只是默認的情況。也就是說在其他情況下,Activity的生命周期可能不會是按照我們以前所知道的流程,本章著重講解Activity的生命周期變化2022-07-07
Android添加glide庫報錯Error: Failed to resolve: com.android.suppo
這篇文章主要給大家介紹了關于Android添加glide庫報錯Error: Failed to resolve: com.android.support:support-annotations:26.0.2的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-11-11
基于Android studio3.6的JNI教程之ncnn人臉檢測mtcnn功能
這篇文章主要介紹了基于Android studio3.6的JNI教程之ncnn之人臉檢測mtcnn功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
android采用FFmpeg實現(xiàn)音頻混合與拼接剪切
這篇文章主要為大家詳細介紹了android采用FFmpeg實現(xiàn)音頻混合與拼接剪切,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
AndroidStudio升級到3.0的新特性和注意事項小結
這篇文章主要介紹了AndroidStudio升級到3.0的新特性和注意事項,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11
Kotlin語言中CompileSdkVersion與targetSdkVersion的區(qū)別淺析
這篇文章主要介紹了Kotlin語言中CompileSdkVersion和targetSdkVersion有什么區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02

