3

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 ?

xyron
  • 75
  • 1
  • 2
  • 6

1 Answers1

3

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. :)

spicydog
  • 1,644
  • 1
  • 17
  • 32
  • This was insightful, will try to implement it and see how this works. – xyron Jun 27 '22 at 16:18
  • "make the native code run in background instead" that's the key and the solution. For Kotlin you can use `CoroutineScope` with `Dispatchers`. – Alex Rintt Feb 27 '23 at 11:37
  • 1
    For me it still doesn't work. I get the following exception: MissingPluginException(No implementation found for method xxx on channel yyy). Looks like I have to make a plugin... – cpper Mar 03 '23 at 23:21
  • i get an MissingPluginException when using this – smedasn May 02 '23 at 20:49