I have a custom view, written in Java and want to use it in my flutter project. Is it possible to convert it to dart-native code or use it as a java class in flutter?
Custom view is quite complex and I am not very experienced in dart language, so would be great to have it either converted to dart or use it as it is
Step 1 : You have to write method channel into dart code:
static Future<void> initSupport({
String? url,
String? appId,
String? clientId,
String? id,
}) async {
await _channel.invokeMethod<void>('initSupport', {
'url': url,
'appId': appId,
'clientId': clientId,
'id': id,
});
}
You have to write into your view where you want to open java view to init this method channel After this, you have to open your project in android studio
Step 2: Check the below code to get method channel from dart
class MainActivity: FlutterFragmentActivity() {
override fun onNewIntent(intent : Intent){
super.onNewIntent(intent)
setIntent(intent)
}
private val CHANNEL = "channelname"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
if(call.method == "initSupport"){
initSupport(call)
result.success(true)
}
}
}
Step 3: method of init is
fun initSupport(call: MethodCall){
val url = call.argument<String>("url") ?: "" // here is your dart data
val appId = call.argument<String>("appId") ?: ""
val clientId = call.argument<String>("clientId") ?: ""
val id = call.argument<String>("id") ?: "1"
// You can init your view here like below
Toast.makeText(this,"hello from native", Toast.LENGTH_SHORT).show()
}