Sub topic 5
Writing the Dart API
This chapter assumes you can write Dart classes, use Future and async/await, and build a Flutter app. It also assumes you understand that native Android and iOS code will implement the channel methods that this Dart API calls.
A plugin's Dart API is the boundary that application developers use. It should hide channel names, method strings, platform message formats, and low-level errors. Callers should work with meaningful classes, return types, and exceptions.
Define the channel contract
Before writing code, define the contract between Dart and native code. The Android and iOS implementations must use the same channel name and method name.
| Part | Value | Purpose |
|---|---|---|
| Channel name | `battery_info` | Identifies the communication channel |
| Method name | `getBatteryLevel` | Requests the current battery percentage |
| Return value | Integer from 0 to 100 | Gives callers a platform-independent result |
| Error code | `UNAVAILABLE` | Reports that the native value cannot be read |
A MethodChannel sends a method call to native code and receives one result. Flutter's standard message codec supports values such as strings, numbers, lists, maps, and null.
Hide channel details behind a class
Keep the channel private. This prevents application code from depending on implementation details and lets you change the native protocol later without changing every caller.
import 'package:flutter/services.dart';
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message);
final String code;
final String? message;
@override
String toString() => 'BatteryInfoException($code, $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');
if (level == null) {
throw BatteryInfoException(
'INVALID_RESULT',
'The platform returned no battery level.',
);
}
return level;
} on PlatformException catch (error) {
throw BatteryInfoException(error.code, error.message);
}
}
}invokeMethod<int> requests an integer result. The nullable type is intentional because a platform message can contain null. Checking it avoids a hidden null assertion and produces a useful plugin-specific error.
The PlatformException contains the error code and message sent by native code. Wrapping it in BatteryInfoException gives callers an exception type that belongs to this package instead of exposing Flutter channel details.
Keep the public API stable
Use methods and types that describe the feature rather than the platform implementation. For example, getBatteryLevel() is better than exposing a raw invokeMethod() call.
A caller can now use the plugin like this:
final batteryInfo = BatteryInfo();
try {
final level = await batteryInfo.getBatteryLevel();
print('Battery: $level%');
} on BatteryInfoException catch (error) {
print('Could not read battery: ${error.message}');
}Document units, valid ranges, and failure behavior. If a future version changes the native implementation from a method channel to generated Pigeon code, callers should not need to change their code.
Exercise
Why should the Dart API check for a null result even though the native implementations are expected to return an integer?
Show answer
A platform message can contain null because of a native bug, an unexpected implementation, or a changed contract. Checking it prevents an unclear null failure and lets the plugin report a deliberate error.