Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to avoid automatic pluggin initialization on Flutter iOS

I'm working with a plugin that I would like to manually register in iOS only if some condition is meet. Right now, the autogenerated AppDelegate.swift registers all plugins included in the pubspect.yaml with this line:

GeneratedPluginRegistrant.register(with: self)

Is there any way to avoid registering a single plugin?

Thank you

like image 455
sajunt4 Avatar asked May 02 '26 14:05

sajunt4


1 Answers

Yes, there is a way (after browsing and reading Flutter iOS engine documentation).

  • write your own plugin in Swift (this language is easier to understand than objC)
  • have AppDelegate.swift file in Swift language too
  • create a plugin in AppDelegate.swift (below the AppDelegate class). This is to make things simple and concise

My code for the plugin:

// TODO: change to our own plugin name
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:
        // TODO: change to our own plugin name
        let registrar = registry.registrar(forPlugin: "flutter_native_timezone")
        if let safeRegistrar = registrar {
            register(with: safeRegistrar)
        }
        
    }
    
    // this is an override of the following function:
    // https://api.flutter.dev/objcdoc/Protocols/FlutterPlugin.html#/c:objc(pl)FlutterPlugin(cm)registerWithRegistrar:
    public static func register(with registrar: FlutterPluginRegistrar) {
        // TODO: change to our own plugin name
        let channel = FlutterMethodChannel(name: "flutter_native_timezone", binaryMessenger: registrar.messenger())

        let instance = FlutterNativeTimezonePlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

  // TODO: add plugin's method calls
  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)
    }
  }
}

Next step:

Below the GeneratedPluginRegistrant.register(with: self) method, add the plugin initialisation: FlutterNativeTimezonePlugin.addManuallyToRegistry(registry: self)

Summary:

This is manual way of adding a plugin to the iOS build. Shame there is no documentation.

like image 146
Michał Dobi Dobrzański Avatar answered May 04 '26 02:05

Michał Dobi Dobrzański