一.Activity中點擊返回鍵
1、Activity
響應(yīng)返回事件赠摇,由onBackPressed
方法處理
@Override
public void onBackPressed() {
if (stillAttachedForEvent("onBackPressed")) {
//delegate為FlutterActivityAndFragmentDelegate實例藕帜,實際負責與Flutter交互的類
delegate.onBackPressed();
}
}
delegate
是FlutterActivityAndFragmentDelegate
的實例,代理Android與Flutter交互的所有事件洽故。
2、FlutterActivityAndFragmentDelegate.onBackPressed()
void onBackPressed() {
...
if (flutterEngine != null) {
...
//getNavigationChannel為NavigationChannel的實例隘弊,把事件傳遞到Flutter端
flutterEngine.getNavigationChannel().popRoute();
} else {
...
}
}
3撞秋、NavigationChannel.popRoute()
public NavigationChannel(@NonNull DartExecutor dartExecutor) {
this.channel = new MethodChannel(dartExecutor, "flutter/navigation", JSONMethodCodec.INSTANCE);
}
public void popRoute() {
...
//將返回事件分發(fā)到Flutter
channel.invokeMethod("popRoute", null);
}
二.Flutter注冊Channel
Flutter
App在啟動時會注冊與Native交互的Channel
//Flutter App的啟動入口
void runApp(Widget app) {
WidgetsFlutterBinding.ensureInitialized()
..scheduleAttachRootWidget(app)
..scheduleWarmUpFrame();
}
class WidgetsFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {}
mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, RendererBinding, SemanticsBinding {
@override
void initInstances() {
super.initInstances();
...
//加載Native NavigationChannel嚣鄙,并處理Navtive傳遞過來的事件
SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
...
}
}
Flutter返回鍵處理哑子,這里popRoute
對應(yīng)Native上點擊返回按鈕
Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) {
switch (methodCall.method) {
case 'popRoute':
//處理返回事件
return handlePopRoute();
case 'pushRoute':
return handlePushRoute(methodCall.arguments as String);
case 'pushRouteInformation':
return _handlePushRouteInformation(methodCall.arguments as Map<dynamic, dynamic>);
}
return Future<dynamic>.value();
}
三.Flutter事件分發(fā)
事件優(yōu)先有Flutter消耗肌割,如果Flutter沒有消耗帐要,最終把事件傳回Native。
Future<void> handlePopRoute() async {
//Flutter內(nèi)部分發(fā)返回事件
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) {
if (await observer.didPopRoute())
return;
}
//如果Flutter不處理奋早,交由Native處理
SystemNavigator.pop();
}
四.Flutter內(nèi)部事件分發(fā)
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) {
if (await observer.didPopRoute())
return;
}
1赠橙、_observers
是一個List<WidgetsBindingObserver>
類型的對象
WidgetsBindingObserver
代碼如下:
abstract class WidgetsBindingObserver {
//在Android中點擊返回鍵時會觸發(fā)這個函數(shù)
//如果返回true表示消費這個事件
Future<bool> didPopRoute() => Future<bool>.value(false);
...
}
2、WidgetsBindingObserver
子類:_WidgetsAppState - WidgetsApp
class WidgetsApp extends StatefulWidget {
//一個好多參數(shù)的構(gòu)造方法
WidgetsApp({
...,
backButtonDispatcher = null,
})
//一個命名構(gòu)造函數(shù)
WidgetsApp.router({
...,
backButtonDispatcher = backButtonDispatcher ?? RootBackButtonDispatcher(),
})
State<WidgetsApp> createState() => _WidgetsAppState();
}
class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
@override
void initState() {
...
//把自身注冊到_observers
WidgetsBinding.instance!.addObserver(this);
}
// On Android: the user has pressed the back button.
//每個頁面的返回事件由這邊處理
@override
Future<bool> didPopRoute() async {
// The back button dispatcher should handle the pop route if we use a router.
//使用MaterialApp.router這個方法才會走到這里
if (_usesRouter)
return false;
//大部分情況下都會走到這~
final NavigatorState? navigator = _navigator?.currentState;
if (navigator == null)
return false;
return navigator.maybePop();
}
}
3掉奄、WidgetsApp
被使用的時機
在使用MaterialApp
時姓建,內(nèi)部會創(chuàng)建WidgetsApp
對象來處理返回事件缤苫,并注冊到_observers
class MaterialApp extends StatefulWidget {
const MaterialApp({...})
const MaterialApp.router({...})
...
@override
State<MaterialApp> createState() => _MaterialAppState();
}
class _MaterialAppState extends State<MaterialApp> {
...
@override
Widget build(BuildContext context) {
Widget result = _buildWidgetApp(context);
...
return ScrollConfiguration(
...
child: HeroControllerScope(
...
child: result,
),
);
}
Widget _buildWidgetApp(BuildContext context) {
...
if (_usesRouter) {
return WidgetsApp.router(...);
}
return WidgetsApp(...);
}
}
4、NavigatorState.maybePop()
處理返回事件活玲,WillPopScope
也會在這個方法進行處理
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;
//WillPopScope會被注冊到這個地方處理
final RoutePopDisposition disposition = await lastEntry.route.willPop(); // this is asynchronous
if (!mounted)
return true; // forget about this pop, we were disposed in the meantime
final _RouteEntry? newLastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (lastEntry != newLastEntry)
return true; // forget about this pop, something happened to our history in the meantime
switch (disposition) {
case RoutePopDisposition.bubble:
return false;
case RoutePopDisposition.pop:
pop(result);
return true;
case RoutePopDisposition.doNotPop:
return true;
}
}
五.事件交由Native處理
//如果Flutter不處理,交由Native處理
SystemNavigator.pop();
//把事件分發(fā)到Native
static Future<void> pop({bool? animated}) async {
await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated);
}
Native接收到Flutter發(fā)送的SystemNavigator.pop
//最終由Android-PlatformPlugin處理
private void popSystemNavigator() {
//FlutterActivity中platformPluginDelegate=null屑柔,所以不會走到此處
if (platformPluginDelegate != null && platformPluginDelegate.popSystemNavigator()) {
// A custom behavior was executed by the delegate. Don't execute default behavior.
return;
}
//最后看到的現(xiàn)象就是Activity退出了~
if (activity instanceof OnBackPressedDispatcherOwner) {
((OnBackPressedDispatcherOwner) activity).getOnBackPressedDispatcher().onBackPressed();
} else {
activity.finish();
}
}