How do you run a task in the background in flutter?

void click() async{
  var a = await platform.invokeMethod('runMyLongFunc');
  print("Done");
  setState(() {});
}

the await there is the key. Although it still runs on the single thread.


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.