Passing parameters Flutter(Dart) <-> Android(Native)

Ganesh L G
2 min readDec 18, 2020

--

The following article describes how to pass parameters and invoke method from native-android to flutter and vice versa with basic “data transfer” example.

Refer to the following link to know basics about the platform specific code from my previous story.

Custom Platform Specific Code(Flutter)-Android Native | by Ganesh L G | Nov, 2020 | Medium

The following code will guide you , how you can actually pass the parameters in both native(kotlin) and dart(flutter).

Client(dart)-main.dart

const platform = const MethodChannel(‘flutter.native/helper’);

Future<void> platfromSpecific(text1,text2) async {

try {

final int result = await platform.invokeMethod(‘flutterToNative’,{“text1”:text1,”text2":text2});

} on PlatformException catch (e) {

print(e.message);

}

}

Future<dynamic> handlePlatformChannelMethods() async {

platform.setMethodCallHandler((methodCall) async {

if (methodCall.method == “nativeToFlutter”) {

String text = methodCall.arguments;

//Parameters received from Native…!!!!

List<String> message = text.split(‘,’);//

String text1 = message[0];

String text2 = message[1];

}

}

}

//Always call the the above function in initState() wherever ur using it…!!!

initState(){

super.initState();

handlePlatformChannelMethods();

}

Native(Kotlin)-MainActivity.kt

class MainActivity: io.flutter.embedding.android.FlutterActivity(){

private val CHANNEL = “flutter.native/helper”

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

super.configureFlutterEngine(flutterEngine)

MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->

// Note: this method is invoked on the main thread.

// TODO

if(call.method == “flutterToNative”){

//Parameters received from dart…!!!!

val text1 = call.argument<String>(“text1”)

val text2 = call.argument<String>(“text2”)

}

}

}

//To invoke method in client(flutter)

fun nativeToFlutter(text1:String?,text2:String?){

MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, CHANNEL).invokeMethod(“nativeToFlutter”,”$text1,$text2");

}

}

Thank you…!!!

--

--

Ganesh L G

Software Engineer(Flutter,Native Android — Mobile Application Developer)