Sub topic 8
Reporting Errors from Native Code to Dart
Prerequisites: You should be comfortable with Dart, Flutter platform channels, Kotlin, and Swift. You should also understand the BatteryInfo plugin’s getBatteryLevel method from the previous chapter.
A platform call can fail after it crosses from Dart into native code. For example, the device might not provide a battery value. Native code must report that failure through the channel. Dart then receives a PlatformException.
The error path
A native method sends one of three responses:
result.success(value)returns a value.result.error(code, message, details)reports a failure on Android.FlutterError(code:message:details:)reports a failure on iOS.
The channel carries the error fields to Dart. The code should be stable because Dart code can use it to decide what to do. The message is useful for logs and debugging. The details value can contain structured information, such as a missing permission or an operating system error.
A method that the native implementation does not recognize should return notImplemented, rather than pretending that it succeeded. Flutter reports that case as a MissingPluginException on the Dart side.
Reporting errors in native code
The Android implementation checks the result before returning it:
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error(
"UNAVAILABLE",
"Battery level not available.",
null
)
}The iOS implementation uses the same error code and message. Keeping these values consistent makes the Dart API platform-independent.
let level = UIDevice.current.batteryLevel
if level < 0 {
result(FlutterError(
code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil
))
} else {
result(Int(level * 100))
}| Native response | Dart result |
|---|---|
| `result.success(42)` | `42` |
| `result.error("UNAVAILABLE", ...)` | `PlatformException` |
| `result.notImplemented()` | `MissingPluginException` |
Wrapping errors in Dart
Do not expose channel details throughout the application. Wrap PlatformException in an exception that belongs to your plugin:
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');
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);
}
}
}This wrapper gives callers a stable exception type even if the channel implementation changes. Callers can handle known codes and show a useful fallback:
try {
final level = await BatteryInfo().getBatteryLevel();
print('$level%');
} on BatteryInfoException catch (error) {
if (error.code == 'UNAVAILABLE') {
print('Battery information is unavailable.');
} else {
rethrow;
}
}Exercise
Why should Android and iOS use the same error code for the same failure?
Show answer
The Dart layer can handle the failure consistently without knowing which platform produced it.