To learn how to use MethodChannel for integrating Kotlin and Dart, we’ll create a prototype Flutter app and extend it in accordance with various practical needs.
First, create a new Flutter project with the following command:
flutter create flutter_android_native cd flutter_android_native
Then we will construct the channel.By declaring the following constant, we will use a MethodChannel with a single platform method:
static const platform = MethodChannel('com.example.flutter_android_native');
Here is a quick example of code that makes use of the MethodChannel and shows how to create a function and call native code.
Retrieve the device’s battery level :
Future<String?> _getBatteryPercentage() async { String batteryPercentage; try { final int result = await platform.invokeMethod('getBatteryPercentage'); batteryPercentage = 'Battery at $result %'; } on PlatformException catch (error) { batteryPercentage = "Failed to get battery level: '${error.message}'"; } return batteryPercentage; }
private fun getBatteryPercentage(): Int { val batteryPercentage: Int if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager batteryPercentage= batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) } else { val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) batteryPercentage= intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) } return batteryPercentage }
While not every application is a good fit for Flutter, having the option to link your app to native code gives you access to more options, safeguards you in the case that a plugin isn’t available or doesn’t match your needs, and raises your value as a Flutter or Native developer. Below is a link to the project’s Github repository. Thanks for reading.
Project link