1 year ago

#356778

test-img

empiresdev

How to send asyncronous response when calling MethodChannel?

Flutter official documentation says we can't use EventChannel for both-direction communication between Flutter and Native code, only on listening events from Native.

So the MethodChannel is the only recommended way to call a method on native from Flutter code. My problem is that I'm using a Thermal Printer that calls an asynchronous routine to print, including internal listeners that run outside the main UI thread. This is the error that I get:

/JavaBinder( 6792): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: Binder_2

That way I can't use a simple Future to return something to Flutter, because I can't send results from listeners.

Question: How can I create an EventChannel whose EventSink can be accessed by a MethodChannel call?

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "unique.identifier.method/call";
    private static final String CHANNEL_STREAM = "unique.identifier.method/stream";
    private Printer printer = new Printer(getApplicationContext());

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
                (call, result) -> {
                    // Note: this method is invoked on the main thread.
                    String method = call.method;
                    if(method == "print"){
                        printer.startPrint(new OnPrintListener.Stub() {
                            public void onFinish() throws RemoteException {
                                printer.cutPaper();
                                //Question: how to send event from this point?
                            }
                            public void onError(int i) throws RemoteException {
                                //Question: how to send error event from this point?
                                throw new RemoteException("Print exception: "+i);
                            }
                        });
                        //it returns true before printing has been finished 
                        result.success(true);
                    }
                }
        );
    }
}

flutter

flutter-method-channel

0 Answers

Your Answer

Accepted video resources