Sub topic 5
Writing the Dart API
This chapter assumes you have generated the battery_info plugin project and know how a MethodChannel carries a call to native code and back. Here you write the Dart side: the class app developers call, and the boundary between their code and the channel.
What the Dart layer is for
App developers should never see a channel name, a method string, or a PlatformException. Those are implementation details shared between Dart, Kotlin and Swift. If they leak into app code, renaming a method becomes a breaking change for every user of the plugin.
The Dart layer has three jobs:
- Hide the channel name and method strings behind ordinary Dart methods and getters.
- Give each call a precise return type.
- Turn channel errors into exceptions that belong to your plugin.
A first version
The class below keeps the channel private and converts platform errors.
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');
return level!;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}
}The string 'battery_info' must match the name used in the Kotlin and Swift code character for character. A mismatch produces no compile error. The call fails at runtime with a MissingPluginException.
Call flow
Choosing return types
invokeMethod<T> takes a type argument, and the result is T?. The type argument does not convert anything. It only casts the value the standard codec already decoded. If the native side sends a Double and you ask for int, the cast fails with a TypeError at runtime.
The standard codec limits what can cross the channel:
| Dart type | Kotlin type | Swift type |
|---|---|---|
| `null` | `null` | `nil` |
| `bool` | `Boolean` | `NSNumber(value: Bool)` |
| `int` | `Int` or `Long` | `NSNumber(value: Int)` |
| `double` | `Double` | `NSNumber(value: Double)` |
| `String` | `String` | `String` |
| `List` | `List` | `Array` |
| `Map` | `HashMap` | `Dictionary` |
For maps and lists, invokeMethod<Map> gives you an untyped Map<dynamic, dynamic>. Use the typed helpers instead:
Future<Map<String, Object?>> getBatteryDetails() async {
final Map<String, Object?>? details =
await _channel.invokeMapMethod<String, Object?>('getBatteryDetails');
return details ?? <String, Object?>{};
}invokeListMethod<T> does the same for lists. Neither helper validates the keys or values inside. They only fix the static types.
A public method should not return a raw Map. Build a small immutable Dart class and construct it from the map inside the plugin. That keeps map keys out of app code. If you later add a field, existing callers still compile.
Passing arguments
invokeMethod accepts one arguments value. For several values, pass a map with string keys:
Future<void> setUpdateInterval(Duration interval) {
return _channel.invokeMethod<void>('setUpdateInterval', <String, Object?>{
'milliseconds': interval.inMilliseconds,
});
}Convert rich Dart types such as Duration, enums, and DateTime to codec types before sending. On the native side, read milliseconds from the call's arguments. Never pass a Dart object and expect the other side to understand it.
Handling null and missing results
The first version uses level!. That throws a generic null-check error if the native side returns nothing, which tells the caller little. A clearer version reports the problem in the plugin's own terms:
Future<int> getBatteryLevel() async {
try {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
if (level == null) {
throw BatteryInfoException('NULL_RESULT', 'Platform returned no value.');
}
return level;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}Reserve Future<int?> for cases where "no value" is a normal answer, such as a sensor that some devices lack. Use a non-nullable type when absence means something went wrong.
Wrapping platform exceptions
The native result.error("UNAVAILABLE", ...) call becomes a PlatformException on the Dart side. Catching it inside the plugin has two benefits. App code only needs to know one exception type, and you can later change what the native side sends without breaking callers.
Copy the code unchanged, as the example does, and document the codes you use. A caller can then branch on UNAVAILABLE without parsing message text. Also keep the original details value if your native code sends structured data, by adding a field to the exception.
Two other failures need a decision:
MissingPluginExceptionis thrown when the native side has no handler for the method. This happens whenresult.notImplemented()is called, when the plugin is not registered, or when the platform has no implementation. It usually signals a programming error or an unsupported platform, so letting it propagate is reasonable.TypeErrorfrom a wrong type argument is a bug in your plugin. Fix it rather than catching it.
Making the class testable
static const ties the class to one real channel, which is fine because tests replace the handler on that channel by name. If you want callers to be able to supply a different channel, accept it in the constructor:
class BatteryInfo {
BatteryInfo({@visibleForTesting MethodChannel? channel})
: _channel = channel ?? const MethodChannel('battery_info');
final MethodChannel _channel;
}This needs import 'package:flutter/foundation.dart'; for visibleForTesting. The default keeps BatteryInfo() working for app developers.
Exporting the public surface
Package users import one file, here package:battery_info/battery_info.dart. Put implementation in lib/src/ and export only the types users need:
export 'src/battery_info.dart' show BatteryInfo;
export 'src/battery_info_exception.dart' show BatteryInfoException;Anything not exported is free to change in a minor release.
Common mistakes
- Using different channel names in Dart, Kotlin and Swift.
- Returning
Future<dynamic>from a public method, which gives callers no type safety. - Leaving out a doc comment (
///) on a public member. The pub.dev score checks for documentation. - Adding a Dart method before the native side handles it on both platforms.
Exercise
The native side sometimes replies result.success(55.0) with a Kotlin Double, but the Dart code calls invokeMethod<int>('getBatteryLevel'). What happens, and how do you fix it?
Show answer
The standard codec decodes the value as a Dart double, and the int cast fails at runtime with a TypeError. The channel does no conversion. Fix it by making both sides agree. Send an Int from Kotlin, for example with level.toInt(), or change the Dart call to invokeMethod<double> and convert it there. Keep the public method's return type unchanged either way.
Exercise
Why does the plugin catch PlatformException and throw BatteryInfoException instead of letting the original exception reach app code?
Show answer
The channel and its error type are implementation details. Wrapping the error gives callers one stable exception type that belongs to the plugin's public API. You can then change how the native side reports errors without breaking app code.