"PluginUtilities"在 Flutter 的 'dart:ui' 库中做了什么,我如何使用它?



PluginUtilities被记录为"Flutter插件作者的功能&";。很难理解它的作用。我应该何时/如何使用它?

PluginUtilities做两件事:

您可以在运行不同代码的完全不同的隔离之间传递这些引用。例如,您可以在隔离a中实现一个方法,为其获取句柄,将句柄传递给隔离B,使用PluginUtilities.getCallbackHandle从该句柄获取方法,并在隔离B中调用该方法。

final handle = PluginUtilities.getCallbackHandle(myLovelyFunctionTearOff); // What is a tear off?: https://stackoverflow.com/questions/69065771/what-is-an-instance-method-tear-off
if (handle == null) {
// function has to be a static method or a top level function. It is null otherwise.
// TODO Show an error to the user to help them fix it.
}

一旦您在单独的隔离中收到句柄,您就可以再次获得该功能:

final function = PluginUtilities.getCallbackFromHandle(handle);
final result = function();

用法示例

Firebase消息会使用它两次,特别是在后台消息中。他们将其用于两个功能:

  • 它们获得用户回调函数的句柄,该函数由用户设置。
    • final CallbackHandle userHandle = PluginUtilities.getCallbackHandle(handler)!;
  • 他们获得了一个附加应用程序入口点的句柄(main函数,他们称之为_firebaseMessagingCallbackDispatcher):
    • final CallbackHandle bgHandle = PluginUtilities.getCallbackHandle(_firebaseMessagingCallbackDispatcher)!;

他们将这些句柄保存到SharedPreferences中,并在应用程序通过推送通知启动时使用它们。这是因为在这种情况下,Flutter应用程序不会自动在Android上启动。服务或广播接收器在不带"活动"的情况下启动,"活动"将启动FlutterEngine和您的应用程序。

当这种情况发生时,Firebase_messaging将使用这些句柄来获取回调函数和应用程序入口点,并启动它们。因此,当您的应用程序未运行时,您的回调仍会被调用,因为它运行一个新的应用程序/入口点(_firebaseMessagingCallbackDispatcher):

void _firebaseMessagingCallbackDispatcher() {
// Initialize state necessary for MethodChannels.
WidgetsFlutterBinding.ensureInitialized();
const MethodChannel _channel = MethodChannel(
'plugins.flutter.io/firebase_messaging_background',
);
// This is where we handle background events from the native portion of the plugin.
_channel.setMethodCallHandler((MethodCall call) async {
/** implementation of method call handling **/
});
// Once we've finished initializing, let the native portion of the plugin
// know that it can start scheduling alarms.
_channel.invokeMethod<void>('MessagingBackground#initialized');

最新更新