Call Flutter from Native Android via Platform Channel in 4 Steps
Flutter allows writing custom platform-specific code. In human language, that means if you have a feature in Android or iOS that is yet supported by Flutter. You can implement that feature using native code. i.e. Kotlin or Java in Android and Object-C or Swift in iOS.
This is a very useful feature. Although there are numerous packages that help to develop a hybrid app with Flutter, there are still some scenarios where we need to dive down to the native land.
One example could be capturing input from Direct Reply Notification. If you are interested in how to implement Direct Reply Notification in Android, you can check out this blog I wrote.
In order to pass the user input from Android to Flutter, we just need to take 4 steps.
4 Steps to call Flutter from Android
- In Android, configure method channel
- In Flutter, configure method channel
- Call Flutter from Android
- Handle method call in Flutter
I have prepared a starting project in here. It’s a Flutter project that takes in user input from Direct Reply Notification. In that way, we can trigger a method call from Android.
If you want to browse the code in the final version, you can check out this repo.
Details
Method channels can invoke method calls as well as receive method calls and send back results. It works in both directions. Most of the tutorials, including the official Flutter tutorial, shows how to call Native Platform from Flutter. This blog will demonstrate how to call Flutter from the Native Platform.
1.In Android, configure method channel
Firstly, let’s create NativeMethodChannel.kt
next to MainActivity.kt
with the following content. It prepares a method channel to invoke methods later.
Then, we call NativeMethodChannel
from MainActivity
to pass in the flutter engine.
2. In Flutter, configure method channel
Similarly in Flutter, we will create a flutter-method-channel.dart
next to main.dart
with the following content.
Then, we call configureChannel
from main.dart
to setup the method channel.
3. Call Flutter from Android
Next, with the method channel ready, we can invoke methods from Android. We will add a method in NativeMethodChannel.kt
.
Next, we can invoke this method in Android. I will invoke it from NotificationReceiver.kt
in this example. But you can invoke it where you need to in your project.
4. Handle method call in Flutter
Finally, we will handle the method call in Flutter. Let’s update flutter-method-channel.dart
. We will set the method handler and update the view when we receive new user input from Android.
Up til now, we have finished passing the value from Native Android to Flutter. For the completeness of this example, we will update the view in Flutter with the value from Android. I will include the data-service.dart
and main.dart
in the following. But they are not required to call Flutter from Native.
Congrats! You have made it to the end.
Happy coding :) Maybe with a cup of coffee~ ☕☕☕