Sub topic 1
Writing a Flutter Plugin Package for Android and iOS
What a plugin is and when you need one
A Flutter plugin is a package that lets Dart code call native code written in Kotlin (Android) or Swift (iOS). A plain Dart package cannot reach device features such as the battery sensor, because those live in the operating system. An FFI package calls C-compatible libraries directly. A plugin is the right choice when the feature needs the Android or iOS SDK.
Use a plugin when you need platform APIs. Use a plain Dart package when pure Dart code is enough.
Prerequisites
You should be comfortable with Dart and Flutter, read basic Kotlin and Swift, and have Android Studio, Xcode, and a working Flutter toolchain installed. You should also know the basics of Gradle and CocoaPods.
Creating the plugin project
Flutter generates the plugin layout for you:
flutter create --template=plugin --platforms=android,ios -a kotlin -i swift --org com.example battery_infoThe generated project contains lib/ for Dart code, android/ and ios/ for native code, and example/ for a sample app.
Telling Flutter about your native code in pubspec.yaml
The flutter.plugin.platforms section of pubspec.yaml names the native class Flutter should register on each platform:
flutter:
plugin:
platforms:
android:
package: com.example.battery_info
pluginClass: BatteryInfoPlugin
ios:
pluginClass: BatteryInfoPluginHow platform channels pass messages
A platform channel is a named message pipe between Dart and native code. Dart sends a method name and arguments. The native side replies with a value or an error. Both sides must use the same channel name, here battery_info.
Writing the Dart API
Hide the channel name and method string behind a Dart class. Callers then see a normal method, and you can convert native errors into your own exception type:
import 'package:flutter/services.dart';
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message);
final String code;
final String? message;
}
class BatteryInfo {
static const MethodChannel _channel = MethodChannel('battery_info');
/// Returns the battery level as a percentage from 0 to 100.
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);
}
}
}Exercise
Your app needs to read the device's compass heading. Should you build a plugin, a plain Dart package, or an FFI package, and why?
Show answer
A plugin. The compass is exposed only through Android and iOS SDKs, so Dart code alone cannot read it. An FFI package would need a C library that exposes the sensor, which is not the usual route for mobile sensors.