While Flutter provides a rich set of cross-platform libraries, you will occasionally need to access platform-specific APIs (such as Bluetooth low-energy, hardware sensors, or custom native SDKs).
This guide explains how to build custom native bridges in Flutter using Platform Channels.
1. Understanding MethodChannel
Flutter uses MethodChannel to pass messages between Dart (Flutter) and native code (Kotlin for Android, Swift for iOS) via asynchronous message passing.
2. Writing Swift Code (iOS)
In your iOS folder, register the MethodChannel inside your App Delegate and listen for method calls:
import Flutter
import UIKit
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",
binaryMessenger: controller.binaryMessenger)
batteryChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if call.method == "getBatteryLevel" {
result(Int(75)) // Return battery level
} else {
result(FlutterMethodNotImplemented)
}
})
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}3. Invoking from Dart
Use the matching channel name to invoke the native method asynchronously in your Dart code. Always handle native exceptions to prevent app crashes.