Flutter: Method Channel vs Event Channel
Flutter provides a platform channel to communicate between the Flutter app and the native platforms. The platform channel consists of two types of channels: Method Channel and Event Channel. Both of these channels allow bi-directional communication meaning a Flutter app can send data to the native platform and receive data back from it. The difference is in how they perform the communication.
Flutter Method Channel
Method channel invokes a method on the native platform and obtains a response from it. The method channel facilitates one-time communication for synchronous operations and allows passing arguments to the invoked method on the native platform. The method on the native platform processes the request. After processing, it returns a result to the Flutter app using the method channel.
Flutter code:
import 'package:flutter/services.dart';
// Define the method channel
const platform = MethodChannel('com.theprogrammingway/battery');
// Invoke the method on the native platform
try {
final int batteryLevel = await platform.invokeMethod('getBatteryLevel');
print('Battery level: $batteryLevel%');
} on PlatformException catch (e) {
print('Failed to get battery level: ${e.message}');
}
Native Platform code (Android)
// Register a method on the native platform to handle the method invocation
new MethodChannel(getFlutterView(), "com.theprogrammingway/battery").setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = // Get the battery level using platform-specific code
// returning the batteryLevel in success
result.success(batteryLevel);
} else {
result.notImplemented();
}
}
}
);
Flutter Event Channel
The event channel receives a stream of events from the native platform. It allows the Flutter application to receive a continuous stream of data by subscribing to an event stream. This makes it an ideal choice for asynchronous communication where we want to receive multiple events from the native platform. Some examples will be sensor or network communication. The event channel in Flutter allows the app to register a listener. Meanwhile, the native platform performs certain actions. The events are transmitted back to the Flutter app by utilizing the event channel.
Flutter Code:
import 'package:flutter/services.dart';
// Define the event channel
const eventChannel = EventChannel('com.example/sensor');
// Register a listener to receive sensor events
eventChannel.receiveBroadcastStream().listen((event) {
print('Received sensor event: $event');
});
Native Platform code (Android)
// Create a sensor manager and register a listener to collect sensor data
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Register the sensor listener and send events through the event channel
sensorManager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// Extract sensor data and send it through the event channel
float[] sensorData = event.values;
eventSink.success(sensorData);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
In summary, Flutter provides two ways to handle communication between the Flutter app and its native platform. One is the method channel, which allows communication once between the Flutter and native platform. The event channel, on the other hand, creates a communication channel between Flutter and the native platform. You can read more on Flutter docs.