Sub topic 3
Reporting errors back to Dart
This chapter assumes you have a Pigeon schema with a HostApi, can write Dart futures, and can read Kotlin or Swift. It covers error reporting, type limits, testing, keeping generated files current, and streaming events.
Reporting errors back to Dart
When native code fails, it throws an error, and Pigeon delivers it to Dart as a PlatformException with a code, a message, and optional details. Use a short, stable code so Dart can branch on it.
// Android: inside your BatteryApiImpl
throw FlutterError("NO_BATTERY", "No battery sensor found", null)// iOS: inside your BatteryApiImpl
throw PigeonError(code: "NO_BATTERY", message: "No battery sensor found", details: nil)try {
final info = await BatteryApi().getBatteryInfo();
print(info.level);
} on PlatformException catch (e) {
print('${e.code}: ${e.message}');
}Supported types and what Pigeon cannot express
Pigeon supports these types in schemas:
bool,int(64-bit),double,StringUint8List,Int32List,Float64Listand similar typed listsListandMapof supported types- Enums and data classes defined in the schema
- Nullable fields, written with
?
Pigeon cannot pass functions or callbacks as arguments. It also does not support method overloading. Data classes are copied across the boundary, so changes on one side do not affect the other.
Testing code that depends on generated APIs
The generated BatteryApi class calls platform channels directly, so unit tests that use it need a native side. Avoid this by putting an interface between your app code and the generated class, then use a fake in tests.
abstract class BatterySource {
Future<BatteryInfo> read();
}Your production implementation wraps BatteryApi. Your tests pass a fake that returns fixed values or throws a PlatformException.
Keeping generated code in sync
Generated files must match the schema at all times.
- Pin the Pigeon version in
pubspec.yaml. - After each schema change, run
dart run pigeon --input pigeons/messages.dart. - Commit the generated files with the schema change.
- In CI, regenerate and run
git diff --exit-codeto fail builds with stale output.
Streaming events from native to Dart
Use @EventChannelApi when native code must push a series of values, such as battery changes. Dart receives these values as a Stream. Cancelling the subscription in Dart stops the native side from sending more events.
Exercise
A native method throws PigeonError(code: "NO_BATTERY", ...). Which Dart exception type catches it, and which property holds the code?
Show answer
It is caught as a PlatformException, and the code is in its code property.