Alexander N.
Alexander N.

Reputation: 1592

What is the correct way to receive a boolean from the StandardMessageCodec?

In the standard codec, it states that bool values are represented as NSNumbers and that when you receive them in iOS, you do so using NSNumber numberWithBool. In my iOS platform specific call (void)handleMethodCall:(FlutterMethodCall *)call I was doing something like this to extract the bool value and use it:

NSNumber *myvalue = [NSNumber numberWithBool:(NSNumber *)call.arguments[@"myvalue"]];
local.object = [myvalue boolValue];

However, I found that no matter the boolean value supplied in my method argument of myvalue that it would always resolve to true. After changing some things, I decided to try to see if I could extract the bool value directly using the code below:

BOOL myvalue = [[call.arguments objectForKey:@"myvalue"] boolValue];
local.object = myvalue;

I was successful, but I wanted to validate that I am doing the correct idiomatic thing. The code that was successful feels like it is running counter to what the flutter documentation states and I just want to validate that I am doing things correctly. Is this okay to do? Should I be doing something else instead?

Upvotes: 0

Views: 274

Answers (1)

Ashkan Sarlak
Ashkan Sarlak

Reputation: 7344

One way is to serialize your messages using protobuf and forget about all these type conversions.

https://pub.dev/packages/protoc_plugin is the dart plugin for protoc command. There is similar plugin for swift/objC. It can generate java/kotlin by default.

In this approach, your data classes for dart and native sides will be generated by protoc. These classes provide an encoder to/decoder from a binary format (i.e. not json or xml or such). You can use these facilities to transmit encoded messages to other side and decode it there into a platform-specific data class.

You can find some tutorial resources, for example take a look at this article: https://medium.com/@er.mayursharma14/setup-protobuf-for-flutter-plugin-method-channel-cdca4018ae09

Upvotes: 1

Related Questions