I have standalone Android App. Then I developed smaller web app in Flutter
and exported it to web server. It is loaded inside WebView
as a part of that standalone App in Kotlin for Android.
Android supports postmessaging and I can send data directly to WebView
through channels. My question is how to listen to these messages in Flutter Dart code (inside my Web App)?
This is code I used in Kotlin Android App:
private var port: WebMessagePort? = null
@TargetApi(Build.VERSION_CODES.M)
private fun initPostMessagePort(){
val channelsAvailable = webView.createWebMessageChannel()
port = channelsAvailable.firstOrNull()
port?.apply {
setWebMessageCallback(object : WebMessageCallback() {
override fun onMessage(port: WebMessagePort, message: WebMessage) {
//TODO do something with message
}
})
}?:kotlin.run {
App.log("Port initialization failed - channels not available")
}
}
@TargetApi(Build.VERSION_CODES.M)
private fun sendMessageToPort(message: String){
port?.let { p->
webView.postWebMessage(WebMessage(message, arrayOf(p)), Uri.EMPTY)
}?:kotlin.run {
App.log("Port not initialized")
}
}
So there is my Flutter Web App startup code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init();
//listen to message from mobile app, then run code below
runApp(MyApp());
bloc.dispatch(GetUserProfile());
}