Utilisation de MethodChanel
Attention ! recompilez dès qu’un changement dans le code a lieu !
Dans le code Flutter :
On défini un canal :
static const platform = MethodChannel('example.com/channel');
On appel le code Kotlin :
int random;
try { random = await platform.invokeMethod('getRandomNumber'); }
on PlatformException
catch (e) { random = 0; }
Dans le code Kotlin :
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "example.com/channel").setMethodCallHandler {
call, result ->
if(call.method == "getRandomString") {
val rand = ('a'..'z').shuffled().take(4).joinToString("")
result.success(rand)
}
else {
result.notImplemented()
}
}
}
Pour passer des paramètres :
Sous Flutter :
Future<void> _generateRandomString() async {
String random = '';
try { var arguments = { 'len': 3, 'prefix': 'fl_', };
random = await platform.invokeMethod('getRandomString', arguments); }
on PlatformException catch (e) { random = ''; }
setState(() { _counter = random; }); }
Sous Kotlin :
if(call.method == "getRandomString") {
val limit = call.argument("len") ?: 4
val prefix = call.argument("prefix") ?: ""
val rand = ('a'..'z')
.shuffled()
.take(limit)
.joinToString(prefix = prefix, separator = "")
result.success(rand)
}
A tester : An example flutter app to show how one can integrate kotlin code in flutter (flutterawesome.com)
Références :
https://docs.flutter.dev/platform-integration/platform-channels
To use Kotlin code in Flutter, you need to use the platform channels mechanism that allows Flutter to communicate with the native code. You can use the MethodChannel class to invoke Kotlin methods from the Dart side and receive the results asynchronously. You can also use the EventChannel class to send events from the Kotlin side to the Dart side. For example:
// Dart side
const platform = MethodChannel('samples.flutter.dev/battery')
try {
final int result = await platform.invokeMethod('getBatteryLevel')
print('Battery level: $result%')
} catch (e) {
print(e)
}
// Kotlin side
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(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 {
// some code to get the battery level
val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager
val batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
println("Battery level: $batteryLevel%")
return batteryLevel
}
}