DEV Community

Cover image for Comprehensive Guide on Using Platform Channels in Flutter
yatendra2001
yatendra2001

Posted on

Comprehensive Guide on Using Platform Channels in Flutter

Yo, Wassup Flutter dev!

Today, we're diving deep into the world of platform channels in Flutter. If you've ever wondered how to harness native capabilities not yet available in the Flutter framework, this guide is for you.

Let's get started!


What are Platform Channels?

In the simplest terms, platform channels provide a bridge between your Dart code and the native code of the host platform (Android or iOS).

This bridge allows Flutter apps to utilize platform-specific features, such as accessing device sensors, invoking native UI components, or integrating third-party SDKs.


Setting the Stage

Before we jump into the code, ensure you have the following:

  • A Flutter app up and running.
  • Basic knowledge of native development (Kotlin/Java for Android and Swift/Objective-C for iOS).

Step-by-Step Guide to Using Platform Channels

1. Define the Channel

In your Dart code, you'll start by defining a MethodChannel. This channel will have a unique name to prevent any conflicts.

import 'package:flutter/services.dart';

const platform = MethodChannel('com.example.myapp/someChannel');
Enter fullscreen mode Exit fullscreen mode

2. Invoke a Method

To request information from the native side, you'll use the invokeMethod function.

String? batteryLevel;

try {
  final int? result = await platform.invokeMethod<int>('getBatteryLevel');
  if (result != null) {
    batteryLevel = 'Battery level: $result%';
  } else {
    batteryLevel = 'Failed to get battery level.';
  }
} on PlatformException catch (e) {
  batteryLevel = "Failed to get battery level: '${e.message}'.";
}
Enter fullscreen mode Exit fullscreen mode

3. Handle the Method Call on the Native Side

Android:

In your MainActivity (Kotlin), override the onMethodCall method:

override fun onMethodCall(call: MethodCall, result: Result) {
  if (call.method == "getBatteryLevel") {
    val batteryLevel = getBatteryLevel()

    if (batteryLevel != -1) {
      result.success(batteryLevel)
    } else {
      result.error("UNAVAILABLE", "Battery level not available.", null)
    }
  } else {
    result.notImplemented()
  }
}

private fun getBatteryLevel(): Int {
  val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
  return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
}
Enter fullscreen mode Exit fullscreen mode

iOS:

In your AppDelegate (Swift), add:

if (call.method == "getBatteryLevel") {
  self.getBatteryLevel(result: result)
} else {
  result(FlutterMethodNotImplemented)
}

private func getBatteryLevel(result: FlutterResult) {
  let device = UIDevice.current
  device.isBatteryMonitoringEnabled = true
  if device.batteryState == UIDevice.BatteryState.unknown {
    result(FlutterError(code: "UNAVAILABLE", message: "Battery info unavailable", details: nil))
  } else {
    result(Int(device.batteryLevel * 100))
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Responding to the Dart Call

Once the native side processes the request, it sends the result back to Dart using the Result object.

You can send a success response with result.success(), an error with result.error(), or indicate that a method isn't implemented with result.notImplemented().


5. Event Channels

For continuous communication or streams, use EventChannel. This is perfect for features like location updates or sensor data.

const eventChannel = EventChannel('com.example.myapp/locationUpdates');
Enter fullscreen mode Exit fullscreen mode

On the Dart side, you can then listen to this channel:

eventChannel.receiveBroadcastStream().listen(_updateLocation);
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

Platform channels are a powerful tool in the Flutter developer's toolkit. They bridge the gap between the Flutter framework and native capabilities, ensuring that you can always access the full power of the underlying platform.

Remember, while platform channels are potent, always consider if there's a Flutter package available that can meet your needs. The Flutter community is vibrant, and there's a good chance someone has already tackled a similar challenge.

Happy coding, and until next time, keep fluttering! 🚀


Before We Go...

Hey, thanks for sticking around! If this post was your jam, imagine what’s coming up next.

I’m launching a YouTube channel, and trust me, you don't want to miss out. Give it a look and maybe even hit that subscribe button?

Tap to subscribe.

Until we meet again, code on and stay curious!

Got any doubt or wanna chat? React out to me on twitter or linkedin.

Top comments (0)