Skip to content

Instantly share code, notes, and snippets.

@ritshpatidar
Created June 26, 2019 17:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ritshpatidar/11310b6c07653df9d8339ff66524e829 to your computer and use it in GitHub Desktop.
Save ritshpatidar/11310b6c07653df9d8339ff66524e829 to your computer and use it in GitHub Desktop.
Connecting Java or Kotlin to Flutter using MethodChannel
package com.example.ourproject
import android.os.Bundle
import io.flutter.plugin.common.MethodChannel
import android.widget.Toast
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
private val CHANNEL = "ourproject.sendstring"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "callSendStringFun") {
showHelloFromFlutter(call.argument("arg"))
val temp = sendString()
result.success(temp)
} else {
result.notImplemented()
}
}
}
private fun sendString(): String {
val stringToSend: String = "Hello from Kotlin"
return stringToSend
}
private fun showHelloFromFlutter(argFromFlutter : String?){
Toast.makeText(this, argFromFlutter, Toast.LENGTH_SHORT).show()
}
}
@sonthichaipks
Copy link

how to write in android code?

@ritshpatidar
Copy link
Author

@sonthichaipks I wrote this code almost 3 years ago. You can read this article .

@GbpJanton
Copy link

I got an error "Unhandled Exception: PlatformException" in release mode but can work on debug mode.
Could you help me plz ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment