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.

EventChannel

The Flutter end

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

var _eventChannel = EventChannel('com.flutter.guide.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;
  @override
  void initState() {
    super.initState();
    _eventChannel.receiveBroadcastStream().listen(_onData);
 }   _onData(event){  setState(() {  _data = event;  });  } Copy the code

Complete code for Flutter end:

class EventChannelDemo extends StatefulWidget {
  @override
  _EventChannelDemoState createState() = _EventChannelDemoState();
}

class _EventChannelDemoState extends StateEventChannelDemo {   var _eventChannel = EventChannel('com.flutter.guide.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, "com.flutter.guide.EventChannel")  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?). {  this.events = events  }   override fun onCancel(arguments: Any?). {  this.events = 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) {
        super.configureFlutterEngine(flutterEngine)
        EventChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
 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: "com.flutter.guide.EventChannel", 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? {  self.events = events  return nil;  }   public func onCancel(withArguments arguments: Any?). - FlutterError? {  self.events = nil  return nil;  }  }   Copy the code

Start in AppDelegate:

import UIKit
import Flutter

@UIApplicationMain
@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

communication

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

Search
About
mo4tech.com (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.