Flutter – PlatformChannel binding methods that returns custom Objects

Issue

I’m playing with PlatformChannel and MethodChannel in Flutter. Doing some basic operations… working on a opencv porting for flutter… but i can’t figure out how to solve this!


There are no problems invoking simple methods, that returns objects of basic Types, like this:

Android:

@Override
  public void onMethodCall(final MethodCall call, final Result result) {
    switch (call.method) {
      case "getVersionString":
        result.success(org.opencv.core.Core.getVersionString());
        break;
      default:
        result.notImplemented();
    }
  }

Dart:

Future<String> get versionString async {
  return await _channel.invokeMethod('getVersionString') as String;
}


But what if i have some custom object? Something like:
Android:

  @Override
  public void onMethodCall(final MethodCall call, final Result result) {
    switch (call.method) {
      case "getVersionString":
        result.success(org.opencv.core.Core.getVersionString());
        break;
      case "Scalar":
        result.success(org.opencv.core.Core.Scalar());
        break;
      default:
        result.notImplemented();
    }
  }
}

Dart:

class Scalar {
  static const MethodChannel _channel = MethodChannel('flutter_opencv');

  // WHAT TO DO HERE??????
}  

How to implement the Scalar dart class? I need to rewrite the class starting from original sources or what?


Thanks for the attenction.

Solution

The StandardMessageCodec can only send certain types across the boundary. Also, you can’t send a Java class across the boundary – what would it turn into at the Dart end?

There are things that you can do:

  1. Serialize the Java object to JSON, transfer the string, then deserialize as a Dart object

  2. Put the Java object’s fields into a HashMap (key is a string, value is a supported type), transfer it (will appear as a Map<String, dynamic>) and access the fields.

  3. Write your own codec (or subclass the standard codec) where you end up basically doing (2) but with less overhead of the string field names. (This is tricky…)

Answered By – Richard Heap

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.