Wednesday, March 27, 2024

Using Method Channel and Event Channel in Flutter for Android(Kotlin) and iOS(Swift)

Here is an English translation:

Introduction to Flutter Method Channel and Event Channel

Flutter provides various mechanisms that enable communication between Dart and native code. Among them, the Method Channel and Event Channel are particularly important.

The Method Channel provides one-way communication between Dart and native code. This allows you to call native functions from Dart and receive the results.

void main(){
  const platform = MethodChannel('samples.flutter.dev/battery');
  String batteryLevel = 'Unknown battery level.';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }
  }
}

On the other hand, the Event Channel provides event-based bidirectional communication between Dart and native code. This allows you to receive and handle events that occur in native code from Dart.

void main(){
  const eventChannel = EventChannel('samples.flutter.dev/connectivity');

  void _enableEventReceiver() {
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  }

  void _onEvent(Object event) {
    setState(() {
      _connectionStatus = event.toString();
    });
  }

  void _onError(Object error) {
    setState(() {
      _connectionStatus = 'Failed to get connectivity.';
    });
  }
}

Using Method Channel and Event Channel in Android (Kotlin)

Let's take a look at how to use the Method Channel and Event Channel to communicate with Flutter on Android. First, let's look at how to use the Method Channel.

void main(){
  MethodChannel channel = MethodChannel("com.example/app")

  channel.setMethodCallHandler { call, result ->
    if (call.method == "getBatteryLevel") {
      val batteryLevel = getBatteryLevel()
      if (batteryLevel != -1) {
        result.success(batteryLevel)
      } else {
        result.error("UNAVAILABLE", "Battery level not available.", null)
      }
    } else {
      result.notImplemented()
    }
  }
}

The above code is an example of receiving a method call from Flutter and processing it in Android (Kotlin). Here, it receives the 'getBatteryLevel' method call and returns the battery level.

Next, let's look at how to use the Event Channel.

void main(){
  EventChannel eventChannel = EventChannel("com.example/app/events")

  eventChannel.setStreamHandler(
    object : StreamHandler {
      private var eventSink: EventChannel.EventSink? = null

      override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        eventSink = events
      }

      override fun onCancel(arguments: Any?) {
        eventSink = null
      }
    }
  )
}

The above code is an example of sending events to Flutter from Android (Kotlin). Here, it sets up an EventSink through the EventChannel, which allows events to be sent.

Using Method Channel and Event Channel in iOS (Swift)

Let's take a look at how to use the Method Channel and Event Channel to communicate with Flutter on iOS. First, let's look at how to use the Method Channel.

void main(){
  let channel = FlutterMethodChannel(name: "com.example/app", binaryMessenger: controller.binaryMessenger)

  channel.setMethodCallHandler {
    (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
    if call.method == "getBatteryLevel" {
      self.receiveBatteryLevel(result: result)
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

The above code is an example of receiving a method call from Flutter and processing it in iOS (Swift). Here, it receives the 'getBatteryLevel' method call and returns the battery level.

Next, let's look at how to use the Event Channel.

void main(){
  let eventChannel = FlutterEventChannel(name: "com.example/app/events", binaryMessenger: controller.binaryMessenger)

  eventChannel.setStreamHandler(self)
}

The above code is an example of sending events to Flutter from iOS (Swift). Here, it sets up a StreamHandler through the EventChannel, which allows events to be sent.


0 개의 댓글:

Post a Comment