Event Channels in Flutter
Recently I was working on a product where I needed to stream data from native (Android / IOS ) to Flutter continuously. By MethodChannel, it is not possible—the Solution Event Channel.
Event Channel: A named channel for communicating with platform plugins using event streams.
First, we need to create Event channel and add events to it.
Android :
IOS :
We have two methods onListen(arg: Any?, sink: EventChannel.EventSink) where the first parameter is the argument, and then eventsink by which we will stream the data from native (Android / IOS ) and onCancel(arg: Any?)
Now we will stream the current time from native (Android / IOS ) to Flutter.
Android: Created Handler for continuous call of function and eventSink.success(data) will send back data to Flutter.
Full Code of MainActivity.kt Android:
IOS: Created Timer.scheduledTimer for continuous call of function and eventSink(data) will send back data to Flutter.
Full Code of AppDelegate.swift IOS:
Flutter main.dart :
First, we will create EventChannel with the same event name on the flutter side.
Method to receive the data continuously from native to flutter.
Displaying data from the stream.
Full Code main.dart Flutter
Complete Code: https://github.com/geek-atif/EventChannel
If you have any questions or suggestions, please leave them in the comments.