I have a Kotlin function that will take a while, and will then return a result (It downloads and parses a file).
I run it from Flutter like this:
void click() {
platform.invokeMethod('runMyLongFunc').then((a) {
print("Done");
setState(() {});
});
}
What should I do for this to run in a background thread (as of now it's blocking on the UI thread).
I tried making click async and it didn't help (void click() async
).
In Flutter, you can execute Dart code in the background. The mechanism for this feature involves setting up an isolate. Isolates are Dart's model for multithreading, though an isolate differs from a conventional thread in that it doesn't share memory with the main program.
Run app in background you can try to get the app running in the background. You must call FlutterBackground. initialize() before calling FlutterBackground. enableBackgroundExecution() .
There are a couple things you could try.
One is to have the Kotlin function do its work in a background thread using one of the methods Android offers for that (AsyncTask
, for example). You could use a MethodChannel to handle the communication between the JVM and Dart, and have the Kotlin code send a message when it was done.
Another possibility is to use a Dart Isolate to multithread on the Dart side. You'd create an Isolate, make the call to Kotlin in its run method, and your other dart code could asynchronously wait for it to be finished on the UI thread while still running the event queue. The Flutter team has an example of how that might work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With