Sub topic 5
Choosing MethodChannel for Request-Response Calls
Assume you know intermediate Dart, Flutter widgets, Future, and asynchronous programming. You should also understand basic Kotlin or Swift syntax. This chapter focuses on choosing MethodChannel when Dart sends a request and native code returns one result.
A MethodChannel is a named communication path between Dart and platform code. Use it for operations such as reading a device setting, requesting a permission, saving a file, or asking a native SDK to perform an action. The call has a request-response shape:
flowchart TD
A[Dart invokes method] --> B[MethodChannel encodes request]
B --> C[Native handler receives call]
C --> D{Operation succeeds?}
D -->|Yes| E[Return result]
D -->|No| F[Return error]
E --> G[Dart Future completes]
F --> Gcaption: MethodChannel request-response flow alt: Dart sends a method call through a channel, native code returns either a result or an error, and a Dart Future completes.
When MethodChannel Fits
Choose MethodChannel when each invocation should produce one completion. The result can be immediate or delayed. The Dart side receives a Future, so it can use await, try, and catch.
| Communication pattern | Suitable channel | Example |
|---|---|---|
| One request and one result | `MethodChannel` | Read the battery level |
| Ongoing native updates | `EventChannel` | Stream sensor readings |
| Two-way, high-volume messaging | Specialized integration | Video or graphics data |
A method name identifies the operation, while arguments carry its inputs. Keep both stable because Dart and native implementations must agree on the contract.
Invoking a Native Method
This wrapper keeps channel details out of widgets and gives callers a typed API:
import 'package:flutter/services.dart';
class GreetingApi {
static const _channel = MethodChannel('com.example.app/greeting');
Future<String> greet(String name) async {
final result = await _channel.invokeMethod<String>('greet', {
'name': name,
});
return result ?? '';
}
}invokeMethod<String> asks the codec to decode the result as a string. The argument map contains only values supported by the channel codec. The returned Future completes when native code calls its result callback.
Handle Failure Explicitly
A missing native handler produces a MissingPluginException. Native code can also return a structured platform error. Catch errors at the application boundary and decide whether to show a message, retry, or use a fallback.
Use MethodChannel instead of an event stream when the caller controls when work starts and expects one answer. If native code produces values independently over time, use EventChannel instead.
Exercise
A Flutter screen asks native code for the current battery percentage each time it opens. Which channel should you choose, and why?
Show answer
Choose MethodChannel because each Dart request expects one native result. Use EventChannel only when the battery value should arrive as an ongoing stream of updates.