π¬Native Integrations
Native integrations are crucial when you need to access platform-specific features or APIs that are not covered by existing Flutter plugins. Let's delve into how you can achieve this in Flutter.
1. Platform Channels:
Platform channels are the bridge between Flutter (Dart) code and the native code (Swift for iOS, Kotlin/Java for Android). They allow you to communicate between these different environments.
a. MethodChannel:
Dart Side:
final channel = MethodChannel('samples.flutter.dev/battery');
Future<void> getBatteryLevel() async {
final int batteryLevel = await channel.invokeMethod('getBatteryLevel');
}final channel = MethodChannel('samples.flutter.dev/battery');- Here, you're creating a newMethodChannelwith a unique namesamples.flutter.dev/battery.getBatteryLevelis a function that will request the battery level from the native side.await channel.invokeMethod('getBatteryLevel');- You're asking the native side to execute a method namedgetBatteryLeveland await its result.
Swift Side:
let channel = FlutterMethodChannel(name: "samples.flutter.dev/battery", binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler {
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
// Handle battery messages.
}let channel = FlutterMethodChannel(name: "samples.flutter.dev/battery", binaryMessenger: controller.binaryMessenger)- This line creates a method channel on the native side with the same name as on the Dart side.channel.setMethodCallHandler { ... }- This sets up a handler for method calls on this channel. When Dart asks forgetBatteryLevel, this handler gets called.
b. EventChannel:
Event channels are used for communication that flows from the native code to Dart.
Dart Side:
final channel = EventChannel('samples.flutter.dev/stream');Here, you're creating a new
EventChannelwith a unique namesamples.flutter.dev/stream.
Swift Side:
let channel = FlutterEventChannel(name: "samples.flutter.dev/stream", binaryMessenger: controller.binaryMessenger)Similar to the
MethodChannel, you create anEventChannelon the native side with the same name as on the Dart side.
2. Creating Platform-Specific Implementations:
Create a new project with platform-specific code using the following command:
flutter create --template=plugin -i swift -a kotlin my_pluginThis command specifies Swift for iOS and Kotlin for Android as the languages to be used for platform-specific code.
3. Handling Platform-Specific Code:
You can handle platform-specific code by creating separate directories for iOS and Android, and placing the respective native code within these directories.
lib/
platform/
android/
android_plugin.dart
ios/
ios_plugin.dart4. Calling Platform-Specific Code:
In your Dart code, you can conditionally call platform-specific code using Platform.isIOS or Platform.isAndroid.
if (Platform.isIOS) {
// Call iOS code
} else if (Platform.isAndroid) {
// Call Android code
}Assignments π
Further Reading π
Last updated
Was this helpful?