Sub topic 6
Returning and handling errors
This chapter assumes you can already call a MethodChannel from Dart and answer it from Kotlin and Swift, as covered in the earlier chapters. It covers what happens when the native side cannot do what Dart asked, and how to turn those failures into predictable Dart behavior.
The three outcomes of a method call
Every invokeMethod call ends in exactly one of three ways. The native handler picks the outcome by which reply it sends.
| Native reply | What Dart sees | Typical meaning |
|---|---|---|
| `result.success(value)` / `result(value)` | The `Future` completes with `value` | The call worked |
| `result.error(code, message, details)` / `FlutterError(...)` | The `Future` completes with a `PlatformException` | The platform understood the call but failed |
| `result.notImplemented()` / `FlutterMethodNotImplemented` | The `Future` completes with a `MissingPluginException` | The platform has no handler for this method |
The two exception types are unrelated. PlatformException means native code ran and reported a failure. MissingPluginException means no native code answered at all.
What a PlatformException carries
A PlatformException has four fields:
codeis a short string such asUNAVAILABLE. Dart code branches on it.messageis a human-readable description. It can be null.detailsis any value the standard codec can encode, such as a map with extra data. It can be null.stacktraceis an optional native stack trace string. Android fills it in when the handler throws an uncaught exception.
Treat code as part of your API. Choose a small, documented set of uppercase codes and use them on both platforms, so Dart code does not need a separate branch per operating system. Never branch on message, because messages differ between platforms and change over time.
details goes through the same codec as any other message, so it must contain only supported types. Putting a native exception object or a custom class in details fails at encoding time. Convert it to a map of strings and numbers first.
Writing the native side
Android
In the Kotlin handler, report expected failures with result.error. Catch exceptions you can anticipate and map each one to a code.
import android.os.BatteryManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val channelName = "com.example.app/battery"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
.setMethodCallHandler { call, result ->
when (call.method) {
"getBatteryLevel" -> {
try {
val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error(
"UNAVAILABLE",
"Battery level not available.",
mapOf("source" to "BatteryManager")
)
}
} catch (e: SecurityException) {
result.error("PERMISSION_DENIED", e.message, null)
}
}
else -> result.notImplemented()
}
}
}
}If the handler throws a RuntimeException that you do not catch, the engine catches it, logs it, and replies with an error whose code is "error", along with the Kotlin stack trace. The app does not crash, but Dart receives a vague code. Catching known exceptions yourself gives Dart a better code.
iOS
Swift handlers cannot propagate a thrown Swift error to Flutter. You have to catch it and convert it to a FlutterError. An Objective-C exception or a force-unwrap failure inside the handler crashes the app, so validate arguments before using them.
import UIKit
import Flutter
enum BatteryError: Error {
case unavailable
}
@main
@objc class AppDelegate: FlutterAppDelegate {
private func readBatteryLevel() throws -> Int {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == .unknown {
throw BatteryError.unavailable
}
return Int(device.batteryLevel * 100)
}
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(
name: "com.example.app/battery",
binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
switch call.method {
case "getBatteryLevel":
do {
guard let level = try self?.readBatteryLevel() else {
result(FlutterError(code: "UNKNOWN", message: "App delegate released.", details: nil))
return
}
result(level)
} catch BatteryError.unavailable {
result(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: ["source": "UIDevice"]))
} catch {
result(FlutterError(code: "UNKNOWN",
message: error.localizedDescription,
details: nil))
}
default:
result(FlutterMethodNotImplemented)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}The default branch matters on both platforms. Without it, an unknown method name leaves the reply uncalled, and the Dart Future never completes.
Handling errors in Dart
Catch the two exception types separately and decide what each one means for your app.
import 'package:flutter/services.dart';
class BatteryUnavailableException implements Exception {
BatteryUnavailableException(this.reason);
final String reason;
@override
String toString() => 'BatteryUnavailableException: $reason';
}
class BatteryService {
static const MethodChannel _channel =
MethodChannel('com.example.app/battery');
/// Returns the battery percentage, or null if this platform has no
/// implementation of the channel.
Future<int?> getBatteryLevel() async {
try {
return await _channel.invokeMethod<int>('getBatteryLevel');
} on MissingPluginException {
return null;
} on PlatformException catch (e) {
switch (e.code) {
case 'UNAVAILABLE':
throw BatteryUnavailableException(e.message ?? 'unknown reason');
default:
rethrow;
}
}
}
}This wrapper does three things:
- It treats a missing implementation as "no value". That suits a feature that is optional on some platforms, such as desktop or web builds that never register the channel.
- It converts a known code into a typed Dart exception. Callers no longer need to know about channel codes.
- It rethrows unknown codes unchanged, so the error is not hidden.
Why MissingPluginException happens
You will see MissingPluginException in these situations:
- The native handler replied
notImplemented, either because the method name is misspelled or because that version of the app does not support it. - The channel name differs between Dart and native code by a single character. Nothing is listening, so the call is treated as unimplemented.
- The app runs on a platform where you never wrote a handler.
- A plugin was added while the app was running, and the app needs a full restart instead of a hot reload or hot restart. Registration of native handlers happens only at startup.
- Code in a background isolate calls a channel that was not set up for that isolate.
Other failure modes to plan for
- Type mismatches.
invokeMethod<int>throws aTypeErrorif native code returns aString. The call succeeded on the platform side, so noPlatformExceptionis involved. A nullable type argument, as ininvokeMethod<int>returningint?, handles a nativenull. - Encoding failures. Sending an unsupported type, such as a custom class in the arguments, throws on the sending side before anything crosses the channel.
- No timeout. A channel call can wait indefinitely if native code is slow or forgets to reply. Add
.timeout(const Duration(seconds: 5))to theFuturewhen a stuck call would block your UI flow, and handleTimeoutException.
Errors in the other direction
Native code can also call Dart through channel.invokeMethod on the native channel object, with Dart handling it through setMethodCallHandler. The same rules apply in reverse. Throw a PlatformException from the Dart handler to send an error reply. Throw MissingPluginException to reply "not implemented". Any other exception thrown by the Dart handler is reported to the native caller as an error with the code "error".
Errors on an EventChannel
An EventChannel has no per-call result, so it reports failures through the stream. When native code calls events.error(code, message, details) (Kotlin) or sends a FlutterError to the event sink (Swift), Dart receives a PlatformException as a stream error. The stream stays open and later events still arrive. Native code ends the stream with endOfStream(), which completes it.
import 'package:flutter/services.dart';
void listenToTicks() {
const events = EventChannel('com.example.app/ticks');
events.receiveBroadcastStream().listen(
(event) => print('tick $event'),
onError: (Object error) {
if (error is PlatformException) {
print('Native stream error ${error.code}: ${error.message}');
}
},
onDone: () => print('Stream ended by native side'),
);
}Without an onError callback, an error event on the stream becomes an uncaught asynchronous error in Dart. Always provide one.
Testing the error path
You can test your error mapping without a device by making the mock handler throw a PlatformException.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
// Assumes BatteryService and BatteryUnavailableException from above
// are imported from your app code.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('com.example.app/battery');
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
test('maps UNAVAILABLE to BatteryUnavailableException', () async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall call) async {
throw PlatformException(
code: 'UNAVAILABLE',
message: 'Battery level not available.',
);
});
expect(
BatteryService().getBatteryLevel(),
throwsA(isA<BatteryUnavailableException>()),
);
});
test('returns null when no handler is registered', () async {
expect(await BatteryService().getBatteryLevel(), isNull);
});
}The second test relies on the fact that, with no mock handler set, the test environment has nothing listening on the channel. The call therefore ends in MissingPluginException, which the service turns into null.
Design checklist
- Define a fixed set of error codes and use the same ones on Android and iOS.
- Reply once on every path, including
catchblocks and early returns. - Always include a
default/elsebranch that replies not implemented. - Keep
detailsto codec-supported types. - Convert
PlatformExceptioninto typed Dart exceptions at the edge of your code, in one wrapper class. - Decide per feature whether
MissingPluginExceptionmeans "unsupported, carry on" or "bug, fail loudly".
Exercise
A Dart call to invokeMethod<int>('getBatteryLevel') never completes and throws nothing. The native handler has a when branch for getBatteryLevel and a catch (e: SecurityException) block. What is the most likely cause, and how do you fix it?
Show answer
Some path through the native handler never calls the reply. For example, the catch block might log the exception but not call result.error, or the method name might fall through a when with no else. Dart waits forever because it only completes when a reply arrives. Fix it by making every branch call exactly one of result.success, result.error, or result.notImplemented, including the catch block and an else branch.
Exercise
Your Dart code catches PlatformException around a call, but the app still crashes with an unhandled MissingPluginException on a desktop build where you wrote no native code. Why, and what is the smallest change that handles it?
Show answer
MissingPluginException does not extend PlatformException, so the on PlatformException clause does not match it. Add a separate on MissingPluginException clause. Return a fallback value there if the feature is optional, or rethrow a clearer error if the feature is required.