Flutter EventChannel

Mahan Yarmohammad
3 min readMar 31, 2022

--

flutter even channel

Intro

There was a problem I encountered trying to use native android listener in flutter, this problem would be common specially if you develop sdks and also if you want to use some native features like phone sensors.

So let’s dive into the main concept and we investigate the code next 👨🏻‍💻

🚧 This blog is the next episode of ‘Flutter MethodChannel’ blog, if you haven’t read it yet, it’s HERE.

EventChannel

‘EventChannels’ are used when the action is triggered from Flutter side like subscribing a listener. This is the second scenario where we want device’s sensor value (in this context the pressure sensor).

Lets dive in:

  1. Create SensorReader Class which inherits ‘EventChannel.StreamHandler

As you can see we register onSensorChanged listener in the ‘initialization’ and then on every sensorChange, we call ‘sensorEventSink.success’ and pass the value

‘onListen’ and ‘onCancel’ are overridden functions of ‘EventChannel.StreamHandler’ which is the handler of our stream

The ‘EventSink’ (java doc) in simple terms is like a publisher which has .success and .error and also acts as a sink of events

So the flow is like this: ‘onSensorChanged’ -> triggers ‘sensorEventSink.success’ with the value -> the ‘EventChannel’ deliver the event to flutter (reflection is used under the hood 🤫) -> finally you get the value thorough EventChannel in dart code

2. Create an EventChannel instance both in Flutter side and native side and subscribe ‘SensorReader’ Class in EventChannel

⚠️ Note:

MethodChannel is used only for initialization of the listener so that the listener is subscribed only when it’s needed

Be aware in this sample project obsolete new instance creation is not checked, so check it in your project.

3. Override onMethodCall in your Activity or Application class to get initialization method call

This is a portion of the original source code I’m not mad enough to use ‘else if’ without an ‘if😂

4. Initialize and set sensor listener in ‘main.dart’

Stream(doc) like Future is a Parameterized type which is used when we deal with a sequence instead of a single value.

Finally use ‘sensorVal’ variable to update sensor value in UI.

Last words

You can use FlutterPlugin instead of FlutterActivity when developing a library and then you should handle android’s context access by another mean.

project’s final result: if you change pressure sensor value, the ui will update immediately

References

Flutter documentation:

Github source code:

--

--

Mahan Yarmohammad

I'm a passionate developer interested in web development, android development, AI, and blockchain.