Sobes.tech
Junior — Middle

How can native code be integrated and called in Flutter applications?

sobes.tech AI

Answer from AI

In Flutter, the mechanism used to invoke native code (in Java/Kotlin for Android and Objective-C/Swift for iOS) is called Platform Channels. It allows message exchange between Dart and native code.

Main steps:

  1. A channel (MethodChannel) is created in Dart with a unique name.
  2. In native code, a handler for this channel is registered, listening for calls from Flutter.
  3. Flutter sends a message with the method call and parameters.
  4. Native code performs the required logic and returns the result.

Example of calling a native method from Flutter:

static const platform = MethodChannel('samples.flutter.dev/battery');

Future<void> getBatteryLevel() async {
  try {
    final int result = await platform.invokeMethod('getBatteryLevel');
    print('Battery level: $result%');
  } on PlatformException catch (e) {
    print('Failed to get battery level: ${e.message}');
  }
}

In Android (Kotlin):

class MainActivity: FlutterActivity() {
  private val CHANNEL = "samples.flutter.dev/battery"

  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
      call, 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(BATTERY_SERVICE) as BatteryManager
    return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  }
}

Thus, Platform Channels provide two-way communication between Flutter and native code.

How can native code be integrated and called in… - sobes.tech