I have setup a basic Method channel in flutter and Kotlin.
Following is my sample data:
{
"user_dob":"15 November 1997",
"user_description":"Hello there, I am a User!",
"user_gender":"Male",
"user_session":"KKDSH3G9OJKJFIHXLJXUGWIOG9UJKLJ98WHIJ"
}
Following method channel can pass the data to Kotlin side from Flutter:
var result = await platform.invokeMethod('updateProfile', data);
Following code catches the data in Kotlin:
MethodChannel(flutterView, channel).setMethodCallHandler { call, result ->
if(call.method == "updateProfile"){
var argData = call.arguments
...
Now,argData contains the data I just sent,
and two questions come up:
How do I access data from argdata? for.eg.
How do I get my user_dob from this argData?
Following code is my current solution.
val userDOB : String = call.argument("user_dob")
But the following error is thrown: Kotlin: Type mismatch: inferred type is String? but String was expected
Note: When I was sending the map data to the MethodChannel, it was accidentally being sent as a String. To follow THIS method through, please make sure that a Map object is implemented in passing the data.
When getting method argument from method channel of Flutter the data that comes in, is a json formatted String.
You can simply call call.argument, and it will return a Nullable string.
In your case you requested for a String which in Kotlin is Nun-null String object, but the returned value of call.argument might not exists in the json and be null. So you must get a String? instead which is a Nullable String.
Update
Check and make sure channel is able to pass data to the native.
In flutter:
static const MethodChannel _channel = const MethodChannel('NAME');
And in native code:
val channel = MethodChannel(registrar.messenger(), "NAME");
TL; DR
In Kotlin use Nullable object for data that can be null.
val userDOB : String? = call.argument("user_dob")
And use it with ?. (Null safe)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With