Flutter:如何避免Flutter iOS上的自动插件初始化

am46iovg  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(188)

我正在使用一个插件,我想在iOS中手动注册它,只有在满足某些条件时。现在,自动生成的AppDelegate.swift使用以下行注册pubspect.yaml中包含的所有插件:

GeneratedPluginRegistrant.register(with: self)

有没有办法避免注册一个插件?
谢谢你

u3r8eeie

u3r8eeie1#

是的,有一种方法(浏览和阅读Flutter iOS引擎文档后)。

  • 用Swift编写插件(这种语言更容易理解。2我不擅长objC ;))
  • AppDelegate.swift(也是Swift语言)
  • AppDelegate.swift中创建插件(在AppDelegate类下面)。这是为了简单起见。在我的例子中是:
public class FlutterNativeTimezonePlugin: NSObject, FlutterPlugin {
    
    public static func addManuallyToRegistry(registry: FlutterPluginRegistry) {
        // https://api.flutter.dev/objcdoc/Protocols/FlutterPluginRegistry.html#/c:objc(pl)FlutterPluginRegistry(im)registrarForPlugin:
        let registrar = registry.registrar(forPlugin: "flutter_native_timezone")
        if let safeRegistrar = registrar {
            register(with: safeRegistrar)
        }
        
    }
    
    // this is an override of this fucnion:
    // https://api.flutter.dev/objcdoc/Protocols/FlutterPlugin.html#/c:objc(pl)FlutterPlugin(cm)registerWithRegistrar:
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "flutter_native_timezone", binaryMessenger: registrar.messenger())
        let instance = FlutterNativeTimezonePlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getLocalTimezone":
      result(NSTimeZone.local.identifier)
    case "getAvailableTimezones":
      result(NSTimeZone.knownTimeZoneNames)
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
  • GeneratedPluginRegistrant.register(with: self)方法下面添加插件初始化方法:FlutterNativeTimezonePlugin.addManuallyToRegistry(registry: self)

所以这是为iOS构建添加插件的手动方式。遗憾的是没有文档。

相关问题