Developing Flutter Plugins
Contents
Architecture & Design Patterns
Federated Plugins
Implement federated plugins to split a plugin's API across multiple packages, allowing independent teams to build platform-specific implementations. Structure federated plugins into three distinct components:
- App-facing interface: The primary package users depend on. It exports the public API.
- Platform interface: The package defining the common interface that all platform implementations must implement.
- Platform implementations: Independent packages containing platform-specific code (e.g.,
my_plugin_android, my_plugin_windows).
FFI vs. Standard Plugins
Choose the correct plugin template based on your native interoperability requirements:
- Standard Plugins (
--template=plugin): Use for accessing platform-specific APIs (e.g., Android SDK, iOS frameworks) via Method Channels.
- FFI Plugins (
--template=plugin_ffi): Use for accessing C/C++ native libraries, configuring Google Play services on Android, or using static linking on iOS/macOS.
- Constraint: FFI plugin packages support bundling native code and method channel registration code, but not method channels themselves. If you require both method channels and FFI, use the standard non-FFI plugin template.
Workflow: Creating a New Plugin
Follow this workflow to initialize a new plugin package.
Task Progress:
Conditional Initialization:
- If creating a STANDARD plugin:
Run the following command, specifying your supported platforms, organization, and preferred languages (defaults are Swift and Kotlin):
flutter create --template=plugin \
--platforms=android,ios,web,linux,macos,windows \
--org com.example.organization \
-i objc -a java \
my_plugin
- If creating an FFI plugin:
Run the following command to generate a project with Dart code in
lib (using dart:ffi) and native source code in src (with a CMakeLists.txt):flutter create --template=plugin_ffi my_ffi_plugin
Workflow: Implementing Android Platform Code
Always edit Android platform code using Android Studio to ensure proper code completion and Gradle synchronization.
Task Progress:
- Generate Build Files:
Build the code at least once before editing to resolve dependencies.
cd example
flutter build apk --config-only
- Open in IDE:
Launch Android Studio and open the
example/android/build.gradle or example/android/build.gradle.kts file.
- Locate Source:
Navigate to your plugin's source code at
java/<organization-path>/<PluginName>.
- Implement V2 Embedding:
- Implement the
FlutterPlugin interface.
- Ensure your plugin class has a public constructor.
- Extract shared initialization logic from the legacy
registerWith() method and the new onAttachedToEngine() method into a single private method. Both entry points must call this private method to maintain backward compatibility without duplicating logic.
- Implement Lifecycle Interfaces:
- If your plugin requires an
Activity reference: Implement the ActivityAware interface and handle the onAttachedToActivity, onDetachedFromActivityForConfigChanges, onReattachedToActivityForConfigChanges, and onDetachedFromActivity callbacks.
- If your plugin runs in a background
Service: Implement the ServiceAware interface.
- Update Example App:
Ensure the example app's
MainActivity.java extends the v2 embedding io.flutter.embedding.android.FlutterActivity.
- Document API:
Document all non-overridden public members in your Android implementation.
Workflow: Implementing Windows Platform Code
Always edit Windows platform code using Visual Studio.
Task Progress:
- Generate Build Files:
cd example
flutter build windows
- Open in IDE:
Launch Visual Studio and open the
example/build/windows/hello_example.sln file.
- Locate Source:
Navigate to
hello_plugin/Source Files and hello_plugin/Header Files in the Solution Explorer.
- Rebuild:
After making changes to the C++ plugin code, you must rebuild the solution in Visual Studio before running the app, or the outdated plugin binary will be used.
Workflow: Adding Platforms to an Existing Plugin
Use this workflow to retrofit an existing plugin with support for additional platforms.
Task Progress:
- Run Create Command:
Navigate to the root directory of your existing plugin and run:
flutter create --template=plugin --platforms=web,macos .
- Update Podspecs:
If adding iOS or macOS support, open the generated
.podspec file and configure the required dependencies and deployment targets.
Examples
Android V2 Embedding Implementation
High-fidelity example of an Android plugin implementing FlutterPlugin and ActivityAware while maintaining legacy compatibility.
package com.example.myplugin;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/** MyPlugin */
public class MyPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
private MethodChannel channel;
// Public constructor required for v2 embedding
public MyPlugin() {}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
setupChannel(flutterPluginBinding.getBinaryMessenger());
}
// Legacy v1 embedding support
public static void registerWith(Registrar registrar) {
MyPlugin plugin = new MyPlugin();
plugin.setupChannel(registrar.messenger());
}
// Shared initialization logic
private void setupChannel(BinaryMessenger messenger) {
channel = new MethodChannel(messenger, "my_plugin");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
// Handle Activity attachment
}
@Override
public void onDetachedFromActivityForConfigChanges() {
// Handle config changes
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
// Handle reattachment
}
@Override
public void onDetachedFromActivity() {
// Clean up Activity references
}
}
1---2name: flutter-building-plugins3description: Builds Flutter plugins that provide native interop for other apps to use. Use when creating reusable packages that bridge Flutter with platform-specific functionality.4---5# Developing Flutter Plugins67## Contents8- [Architecture & Design Patterns](#architecture--design-patterns)9- [Workflow: Creating a New Plugin](#workflow-creating-a-new-plugin)10- [Workflow: Implementing Android Platform Code](#workflow-implementing-android-platform-code)11- [Workflow: Implementing Windows Platform Code](#workflow-implementing-windows-platform-code)12- [Workflow: Adding Platforms to an Existing Plugin](#workflow-adding-platforms-to-an-existing-plugin)13- [Examples](#examples)1415## Architecture & Design Patterns1617### Federated Plugins18Implement federated plugins to split a plugin's API across multiple packages, allowing independent teams to build platform-specific implementations. Structure federated plugins into three distinct components:191. **App-facing interface:** The primary package users depend on. It exports the public API.202. **Platform interface:** The package defining the common interface that all platform implementations must implement.213. **Platform implementations:** Independent packages containing platform-specific code (e.g., `my_plugin_android`, `my_plugin_windows`).2223### FFI vs. Standard Plugins24Choose the correct plugin template based on your native interoperability requirements:25* **Standard Plugins (`--template=plugin`):** Use for accessing platform-specific APIs (e.g., Android SDK, iOS frameworks) via Method Channels.26* **FFI Plugins (`--template=plugin_ffi`):** Use for accessing C/C++ native libraries, configuring Google Play services on Android, or using static linking on iOS/macOS. 27 * *Constraint:* FFI plugin packages support bundling native code and method channel registration code, but *not* method channels themselves. If you require both method channels and FFI, use the standard non-FFI plugin template.2829## Workflow: Creating a New Plugin3031Follow this workflow to initialize a new plugin package.3233**Task Progress:**34- [ ] Determine if the plugin requires FFI or standard Method Channels.35- [ ] Execute the appropriate `flutter create` command.36- [ ] Verify the generated directory structure.3738**Conditional Initialization:**39* **If creating a STANDARD plugin:**40 Run the following command, specifying your supported platforms, organization, and preferred languages (defaults are Swift and Kotlin):41 ```bash42 flutter create --template=plugin \43 --platforms=android,ios,web,linux,macos,windows \44 --org com.example.organization \45 -i objc -a java \46 my_plugin47 ```48* **If creating an FFI plugin:**49 Run the following command to generate a project with Dart code in `lib` (using `dart:ffi`) and native source code in `src` (with a `CMakeLists.txt`):50 ```bash51 flutter create --template=plugin_ffi my_ffi_plugin52 ```5354## Workflow: Implementing Android Platform Code5556Always edit Android platform code using Android Studio to ensure proper code completion and Gradle synchronization.5758**Task Progress:**59- [ ] Run initial build to generate necessary Gradle files.60- [ ] Open the Android module in Android Studio.61- [ ] Implement `FlutterPlugin` and lifecycle-aware interfaces.62- [ ] Refactor legacy `registerWith` logic.63- [ ] Run validator -> review errors -> fix.64651. **Generate Build Files:**66 Build the code at least once before editing to resolve dependencies.67 ```bash68 cd example69 flutter build apk --config-only70 ```712. **Open in IDE:**72 Launch Android Studio and open the `example/android/build.gradle` or `example/android/build.gradle.kts` file.733. **Locate Source:**74 Navigate to your plugin's source code at `java/<organization-path>/<PluginName>`.754. **Implement V2 Embedding:**76 * Implement the `FlutterPlugin` interface.77 * Ensure your plugin class has a public constructor.78 * Extract shared initialization logic from the legacy `registerWith()` method and the new `onAttachedToEngine()` method into a single private method. Both entry points must call this private method to maintain backward compatibility without duplicating logic.795. **Implement Lifecycle Interfaces:**80 * **If your plugin requires an `Activity` reference:** Implement the `ActivityAware` interface and handle the `onAttachedToActivity`, `onDetachedFromActivityForConfigChanges`, `onReattachedToActivityForConfigChanges`, and `onDetachedFromActivity` callbacks.81 * **If your plugin runs in a background `Service`:** Implement the `ServiceAware` interface.826. **Update Example App:**83 Ensure the example app's `MainActivity.java` extends the v2 embedding `io.flutter.embedding.android.FlutterActivity`.847. **Document API:**85 Document all non-overridden public members in your Android implementation.8687## Workflow: Implementing Windows Platform Code8889Always edit Windows platform code using Visual Studio.9091**Task Progress:**92- [ ] Run initial build to generate the Visual Studio solution.93- [ ] Open the solution in Visual Studio.94- [ ] Implement C++ logic.95- [ ] Rebuild the solution.96971. **Generate Build Files:**98 ```bash99 cd example100 flutter build windows101 ```1022. **Open in IDE:**103 Launch Visual Studio and open the `example/build/windows/hello_example.sln` file.1043. **Locate Source:**105 Navigate to `hello_plugin/Source Files` and `hello_plugin/Header Files` in the Solution Explorer.1064. **Rebuild:**107 After making changes to the C++ plugin code, you *must* rebuild the solution in Visual Studio before running the app, or the outdated plugin binary will be used.108109## Workflow: Adding Platforms to an Existing Plugin110111Use this workflow to retrofit an existing plugin with support for additional platforms.112113**Task Progress:**114- [ ] Run the platform addition command.115- [ ] Update iOS/macOS podspecs (if applicable).116- [ ] Implement the platform-specific code.1171181. **Run Create Command:**119 Navigate to the root directory of your existing plugin and run:120 ```bash121 flutter create --template=plugin --platforms=web,macos .122 ```1232. **Update Podspecs:**124 If adding iOS or macOS support, open the generated `.podspec` file and configure the required dependencies and deployment targets.125126## Examples127128### Android V2 Embedding Implementation129High-fidelity example of an Android plugin implementing `FlutterPlugin` and `ActivityAware` while maintaining legacy compatibility.130131```java132package com.example.myplugin;133134import androidx.annotation.NonNull;135import io.flutter.embedding.engine.plugins.FlutterPlugin;136import io.flutter.embedding.engine.plugins.activity.ActivityAware;137import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;138import io.flutter.plugin.common.MethodCall;139import io.flutter.plugin.common.MethodChannel;140import io.flutter.plugin.common.MethodChannel.MethodCallHandler;141import io.flutter.plugin.common.MethodChannel.Result;142import io.flutter.plugin.common.PluginRegistry.Registrar;143144/** MyPlugin */145public class MyPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {146 private MethodChannel channel;147148 // Public constructor required for v2 embedding149 public MyPlugin() {}150151 @Override152 public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {153 setupChannel(flutterPluginBinding.getBinaryMessenger());154 }155156 // Legacy v1 embedding support157 public static void registerWith(Registrar registrar) {158 MyPlugin plugin = new MyPlugin();159 plugin.setupChannel(registrar.messenger());160 }161162 // Shared initialization logic163 private void setupChannel(BinaryMessenger messenger) {164 channel = new MethodChannel(messenger, "my_plugin");165 channel.setMethodCallHandler(this);166 }167168 @Override169 public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {170 if (call.method.equals("getPlatformVersion")) {171 result.success("Android " + android.os.Build.VERSION.RELEASE);172 } else {173 result.notImplemented();174 }175 }176177 @Override178 public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {179 channel.setMethodCallHandler(null);180 }181182 @Override183 public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {184 // Handle Activity attachment185 }186187 @Override188 public void onDetachedFromActivityForConfigChanges() {189 // Handle config changes190 }191192 @Override193 public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {194 // Handle reattachment195 }196197 @Override198 public void onDetachedFromActivity() {199 // Clean up Activity references200 }201}202```