Moment For Technology

Flutter hybrid development with native communication -EventChannel

Posted on Aug. 8, 2022, 8:13 p.m. by Eva Barr
Category: android Tag: flutter

The Flutter hybrid development family includes the following:

  • Embed native View-Android
  • Embed native View-ios
  • Communicate with native -MethodChannel
  • Communicate with native -BasicMessageChannel
  • Communicate with native -EventChannel
  • Add Flutter to Android Activity
  • Add Flutter to Android Fragment
  • Add Flutter to iOS

Share one article every weekday, welcome to follow, like and forward.


The Flutter end

The Flutter end creates an EventChannel to communicate with the native end:

var _eventChannel = EventChannel('');
Copy the code

Com. Flutter. Guide the EventChannel is EventChannel, the name of the primary side and the matching.

Listen for messages sent from the native end:

var _data;
  void initState() {
 }   _onData(event){  setState(() {  _data = event;  });  } Copy the code

Complete code for Flutter end:

class EventChannelDemo extends StatefulWidget {
  _EventChannelDemoState createState() = _EventChannelDemoState();

class _EventChannelDemoState extends StateEventChannelDemo {   var _eventChannel = EventChannel('');  var _data;  @override  void initState() {  super.initState();  _eventChannel.receiveBroadcastStream().listen(_onData);  }   _onData(event){  setState(() {  _data = event;  });  }   @override  Widget build(BuildContext context) {  return Scaffold(  appBar: AppBar(),  body: Center(  child: Text('$_data'),  ),  );  } }  Copy the code

The Android end

Create EventChannelDemo on Android:

class EventChannelDemo(var activity: Activity, messenger: BinaryMessenger):EventChannel.StreamHandler {
    private var channel: EventChannel
    private var index = 0
    private var events: EventChannel.EventSink? = null
    init {
 channel = EventChannel(messenger, "")  channel.setStreamHandler(this)  startTimer()  }    fun startTimer(a) {  var timer = Timer().schedule(timerTask {  index++  var map = mapOf("name" to "laomeng${index}". "age" to "${index}"  )  activity.runOnUiThread { events? .success(map) }   }, 0.1000)   }   override fun onListen(arguments: Any? , events:EventChannel.EventSink?). { = events  }   override fun onCancel(arguments: Any?). { = null  } } Copy the code

events? The.success(map) method sends data to the Flutter end. This method must be executed on the main thread:

activity.runOnUiThread {
events? .success(map)}
Copy the code

Start in MainActivity:

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
 flutterEngine.plugins.add(MyPlugin())  } } Copy the code

The iOS side

To create MethodChannelDemo on ios, do as follows:

import Flutter
import UIKit

public class EventChannelDemo:NSObject.FlutterStreamHandler{
 var channel:FlutterEventChannel?  var count = 0  var events:FlutterEventSink?   public override init() {  super.init(a) }   convenience init(messenger: FlutterBinaryMessenger) {   self.init(a)  channel = FlutterEventChannel(name: "", binaryMessenger: messenger) channel? .setStreamHandler(self)  startTimer()  }   func startTimer(a) {  let timer = Timer.scheduledTimer(timeInterval:1, target: self, selector:#selector(self.tickDown),userInfo:nil,repeats: true)  }  @objc func tickDown(a){  count+ =1  let args = ["count":count]  if(events ! =nil) {events! (args) }  }   public func onListen(withArguments arguments: Any? , eventSink events: @escaping FlutterEventSink) - FlutterError? { = events  return nil;  }   public func onCancel(withArguments arguments: Any?). - FlutterError? { = nil  return nil;  }  }   Copy the code

Start in AppDelegate:

import UIKit
import Flutter

@objc class AppDelegate: FlutterAppDelegate {
 override func application(  _ application: UIApplication,  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?  ) - Bool {   let controller : FlutterViewController= window? .rootViewControlleras! FlutterViewController  EventChannelDemo(messenger: controller.binaryMessenger)  GeneratedPluginRegistrant.register(with: self)   return super.application(application, didFinishLaunchingWithOptions: launchOptions)  } }  Copy the code


Lao Meng Flutter blog (330 controls usage + practical primer series) :

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.