Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 937
Charles Shiller Avatar asked Feb 28 '18 23:02

Charles Shiller


People also ask

Can Flutter run in the background?

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.

How do I know if an app is running in the background Flutter?

Run app in background you can try to get the app running in the background. You must call FlutterBackground. initialize() before calling FlutterBackground. enableBackgroundExecution() .


1 Answers

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.

like image 160
RedBrogdon Avatar answered Oct 07 '22 16:10

RedBrogdon