Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter plugin: "Methods marked with @UiThread must be executed on the main thread."

I am creating Flutter plugin. There are few channels on which I am sending the callbacks from Android to Flutter. Situation is that I am listening for some events which are triggered in OTHER thread than main UI thread.

After recent Flutter update I starting to receive such an error

E/AndroidRuntime( 9400): FATAL EXCEPTION:  STARTING
E/AndroidRuntime( 9400): Process: com.northernbitcoin.coinyacapp, PID: 9400
E/AndroidRuntime( 9400): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread:  STARTING
E/AndroidRuntime( 9400):    at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:794)
E/AndroidRuntime( 9400):    at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:684)
E/AndroidRuntime( 9400):    at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:80)
E/AndroidRuntime( 9400):    at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:174)
E/AndroidRuntime( 9400):    at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:144)
E/AndroidRuntime( 9400):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler$EventSinkImplementation.success(EventChannel.java:226)
...

Only information I found is here https://github.com/flutter/flutter/issues/34993

Yes, there are a solution here https://github.com/flutter/flutter/issues/34993#issue-459900986

But it looks like too overhead for me, because I dont't want to create new handler for each my event

Is there any other solutions?

like image 318
Airon Tark Avatar asked Mar 15 '26 13:03

Airon Tark


1 Answers

Do the same as in suggested solution above, but use it for particular events only.

Create ui handler object

public class BitcoinWalletPlugin implements MethodCallHandler, ... {

  private Handler uiThreadHandler = new Handler(Looper.getMainLooper());

  @Override
  public void onListen(Object o, EventChannel.EventSink eventSink) {
    switch (this.channel) {
      ...
      case CHANNEL_NAME:
        // before
        // bitcoinWallet.setOnStartupListener(() -> eventSink.success(true));

        // after
        bitcoinWallet.setOnStartupListener(() -> uiThreadHandler.post(() -> eventSink.success(true)));
        break;
    }
  }

}

like image 193
Airon Tark Avatar answered Mar 17 '26 04:03

Airon Tark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!