Sub topic 16
Splitting a plugin into a federated package set
This chapter assumes you have finished the earlier chapters. You should have a working battery_info plugin with a MethodChannel, Kotlin and Swift implementations, and pubspec.yaml platform entries. You should also be comfortable with Dart packages, pubspec.yaml dependencies, and running flutter pub get and flutter test.
Why federate
A single plugin package holds the Dart API, the Android code and the iOS code. That works well while you own every platform. It gets awkward when:
- Another team or contributor wants to add Linux, Windows or web support but cannot publish to your package.
- You want to release an Android fix without re-releasing iOS code.
- Several implementations of the same API should be able to exist, for example one backed by a different native library.
A federated plugin splits the plugin into several packages so each platform can be written, versioned and published independently. Apps still depend on one package and call one API.
The four package roles
| Package | Example name | Contains |
|---|---|---|
| App-facing | `battery_info` | The public Dart API that apps import. It has no native code. |
| Platform interface | `battery_info_platform_interface` | An abstract class that every implementation extends, plus a default `MethodChannel` implementation. |
| Android implementation | `battery_info_android` | Kotlin code and its Dart registration class. |
| iOS implementation | `battery_info_ios` | Swift code and its Dart registration class. |
An implementation package is called endorsed when the app-facing package lists it as a dependency and names it as the default for a platform. Apps get endorsed implementations automatically. A package that implements the interface but is not listed (for example a community battery_info_linux) is unendorsed. App authors add it to their own pubspec.yaml by hand.
Suggested layout
Keep the packages as siblings in one repository so you can change them together.
battery_info/
battery_info/ app-facing, with an example app
battery_info_platform_interface/
battery_info_android/
battery_info_ios/Create the Dart-only packages with flutter create --template=package. Create each implementation package with --template=plugin and only its own platform, for example --platforms=android -a kotlin.
The platform interface package
This package depends on plugin_platform_interface. Its base class PlatformInterface stops other code from replacing the active implementation with an object that merely implements the interface.
import 'package:flutter/services.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
abstract class BatteryInfoPlatform extends PlatformInterface {
BatteryInfoPlatform() : super(token: _token);
static final Object _token = Object();
static BatteryInfoPlatform _instance = MethodChannelBatteryInfo();
static BatteryInfoPlatform get instance => _instance;
static set instance(BatteryInfoPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
Future<int> getBatteryLevel() {
throw UnimplementedError('getBatteryLevel() has not been implemented.');
}
}
class MethodChannelBatteryInfo extends BatteryInfoPlatform {
static const MethodChannel _channel = MethodChannel('battery_info');
@override
Future<int> getBatteryLevel() async {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
return level!;
}
}Three details matter here:
- The
tokenis private to the package.verifythrows if an instance was built without callingsuper(token: ...), which is what happens when someone usesimplements. - The default value of
_instanceis theMethodChannelversion. If a platform has no registered implementation, the call falls through to a channel that nobody answers, which yields aMissingPluginException. - New methods on the base class should throw
UnimplementedErrorrather than being abstract. Adding an abstract method later would break every existing implementation. Throwing keeps the change non-breaking.
Move BatteryInfoException into this package too, so every implementation can throw the same type.
The app-facing package
The public class becomes a thin wrapper. Apps keep the same BatteryInfo().getBatteryLevel() call as before.
import 'package:battery_info_platform_interface/battery_info_platform_interface.dart';
export 'package:battery_info_platform_interface/battery_info_platform_interface.dart'
show BatteryInfoException;
class BatteryInfo {
Future<int> getBatteryLevel() {
return BatteryInfoPlatform.instance.getBatteryLevel();
}
}Its pubspec.yaml has no native class. It names the endorsed implementations and depends on all of them:
name: battery_info
description: Reads the battery level on Android and iOS.
version: 1.0.0
environment:
sdk: ^3.0.0
flutter: ">=3.10.0"
flutter:
plugin:
platforms:
android:
default_package: battery_info_android
ios:
default_package: battery_info_ios
dependencies:
flutter:
sdk: flutter
battery_info_platform_interface: ^1.0.0
battery_info_android: ^1.0.0
battery_info_ios: ^1.0.0An implementation package
The implementation package keeps the Kotlin or Swift code from the earlier chapters unchanged. Two things change: the pubspec.yaml and a small Dart class that registers the implementation.
name: battery_info_android
description: Android implementation of the battery_info plugin.
version: 1.0.0
environment:
sdk: ^3.0.0
flutter: ">=3.10.0"
flutter:
plugin:
implements: battery_info
platforms:
android:
package: com.example.battery_info_android
pluginClass: BatteryInfoAndroidPlugin
dartPluginClass: BatteryInfoAndroid
dependencies:
flutter:
sdk: flutter
battery_info_platform_interface: ^1.0.0implements: battery_info tells the tool which plugin this package supplies a platform for. dartPluginClass names a Dart class with a static registerWith() method. The generated plugin registrant calls it at startup, before main runs.
import 'package:battery_info_platform_interface/battery_info_platform_interface.dart';
import 'package:flutter/services.dart';
class BatteryInfoAndroid extends BatteryInfoPlatform {
static const MethodChannel _channel = MethodChannel('battery_info');
static void registerWith() {
BatteryInfoPlatform.instance = BatteryInfoAndroid();
}
@override
Future<int> getBatteryLevel() async {
try {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
return level!;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}
}The channel name must match the one in BatteryInfoAndroidPlugin.kt. The iOS package is identical except for the class name (BatteryInfoIos), the ios: block in its pubspec.yaml (which has no package: line), and the Swift class.
Developing and testing locally
While the packages are unpublished, the app-facing package cannot resolve ^1.0.0 from pub.dev. Point it at the siblings with overrides:
dependency_overrides:
battery_info_platform_interface:
path: ../battery_info_platform_interface
battery_info_android:
path: ../battery_info_android
battery_info_ios:
path: ../battery_info_iosRemove the overrides before publishing. Run the example app inside the app-facing package, since that is the one apps will depend on.
To test the app-facing package without a device, install a fake. Because the fake extends the interface through a mixin, it passes verify:
import 'package:battery_info/battery_info.dart';
import 'package:battery_info_platform_interface/battery_info_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
class FakeBatteryInfoPlatform extends BatteryInfoPlatform
with MockPlatformInterfaceMixin {
@override
Future<int> getBatteryLevel() async => 77;
}
void main() {
test('BatteryInfo forwards to the platform instance', () async {
BatteryInfoPlatform.instance = FakeBatteryInfoPlatform();
expect(await BatteryInfo().getBatteryLevel(), 77);
});
}Test each implementation package with the mocked-channel approach from the testing chapter.
Publishing order and versioning
Publish in dependency order, because pub.dev must be able to resolve each package's dependencies:
- Publish
battery_info_platform_interface. - Publish
battery_info_androidandbattery_info_ios. - Remove
dependency_overridesand publishbattery_info.
Run flutter pub publish --dry-run in each package first. Follow semantic versioning for the interface package carefully. A breaking change there forces a major version in every implementation, so prefer adding methods that throw UnimplementedError.
Common problems
| Symptom | Likely cause |
|---|---|
| `MissingPluginException` on one platform | The implementation package is not a dependency, or the channel names on the Dart and native sides differ. |
| `AssertionError` about the token when setting `instance` | The class uses `implements` instead of `extends`, or a test fake lacks `MockPlatformInterfaceMixin`. |
| `registerWith` never runs | `dartPluginClass` is missing from the implementation's `pubspec.yaml`, or you did not rebuild after changing it. |
| `pub get` fails on `^1.0.0` | The siblings are unpublished and `dependency_overrides` is missing. |
Exercise
A contributor publishes battery_info_linux, which extends BatteryInfoPlatform and has implements: battery_info in its pubspec. The app-facing battery_info package does not list it. What must an app author do to use it on Linux, and why?
Show answer
The app author must add battery_info_linux to the app's own dependencies. The app-facing package only endorses Android and iOS through default_package, so the Flutter tool does not pull in the Linux package by itself. Once the app depends on it, the tool sees implements: battery_info and registers it on Linux.
Exercise
Why does BatteryInfoPlatform use extends PlatformInterface with a token instead of being a plain abstract class?
Show answer
The token and PlatformInterface.verify reject instances that were created with implements. Such instances skip the base class constructor, so they would not inherit methods added in later versions of the interface, and calls to those methods would crash. Requiring extends makes new methods fall back to the base class behavior, which throws UnimplementedError.