Mystery of Channels in Flutter and relation with Native Implementation
Hi there!, hope you guys are doing well. As a Flutter developer, I’m often confused about the different terminologies and implementations used when native channels are involved. This confusion is natural as we have different channels for different purposes if we want to communicate with Native API’s.
For example, If we need some data like gyro sensitivity, hardware sensor data and things which will be frequently updated we use Event channels to clear that purpose.
double getDeviceAcceleration() {
Event.invokeEventChannelAndroid();
Event.invokeEventChanneliOS();
}
As seen above, this pseudocode powerfully illustrates the use case scenario of Event Channels and where should we use them.
UNDERSTAND THE PROBLEM AND THEN CHOOSE THE TOOLS
Now let’s consider another scenario where we need to access some native code written on Android or iOS or some package whose implementation is on Native code and is uavailable in Flutter.
For example, we need access to methods like getDeviceAcceleration() or getBatteryPercentage() or getOSFeatures() which are already written on the native side. Then we will use Method channels for these purposes.
static Future<double> getBatteryPercentage() async {
final result = await methodChannel
.invokeMethod<int>('getbatteryPercentage');
return result!;
}
final value = await MethodChannelX.getBatteryPercentage();
Below pseduo-snippets show how the implementaion occurs from native as well as dart-side.
Similarly, we can also load an image from a native asset using Platform Image which uses a BasicMessageChannel
using StandardMessageCodec
to load an image from native asset.
We can also create Basic Message Channel using JSONMessageCodec
, BinaryCodec
and StringCodec
types to send and receive data about anything.
So According to use cases, different applications of channels come into play. To summarise, I’ve listed them below:
Method Channel (Click For demo)
Event Channel (Click For demo)
Platform Image (Click For demo)
Basic Message Channel(Click For demo)
Thank you, let me know if you have any issues understanding the concept.