Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a platform code from an isolate in flutter?

I know these libraries flutter_isolate and isolate_handler exist that support doing these but I couldn't find any method to call platform specific codes from inside of them. Can someone show any example of how it's done ?

like image 575
xyron Avatar asked Feb 17 '26 02:02

xyron


1 Answers

My answer might not answer to your question directly but I was facing the same situation. I was working on this to run a computing intensive task avoiding UI lagging. After a long research, no, you cannot run Platform from other isolates rather than the main one.

Instead of making and running the native code on another isolate, let's make the native code run in background instead with TaskQueue. Channels and platform threading

The example code in the above link is using onAttachedToEngine, you can check it out. However, I was using is configureFlutterEngine so I have to figure out a little bit until I found a solution that I need binaryMessenger to make it working. Luckily it can called from flutterEngine too!

This is the example code of when using configureFlutterEngine

class MainActivity: FlutterFragmentActivity() {

    val MOBILE_SDK_CHANNEL = "com.example.app/flutter"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);

        super.configureFlutterEngine(flutterEngine)
        val taskQueue = flutterEngine.dartExecutor.binaryMessenger.makeBackgroundTaskQueue()

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, MOBILE_SDK_CHANNEL,
                StandardMethodCodec.INSTANCE, taskQueue).setMethodCallHandler { call, result ->
            // TODO : Do implementation here
            when (call.method) {
                "example_method" -> {
                    // success
                    // result.success(data)
                }
                else -> result.notImplemented()
            }
        }
    }
}

With taskQueue the native code will be ready to run in background.

Future<void> getData() async {
  if (Platform.isAndroid) {
    const platform = MethodChannel("com.example.app/flutter");
    var data = await platform.invokeMethod("example_method");
    // data is ready to use and non-blocked the UI thread
    return data
  }
}

The native code now runs in non-blocking manner, no more UI lag. :)

like image 200
spicydog Avatar answered Feb 20 '26 00:02

spicydog



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!