Can flutter isolates be safely instantiated above runApp()

599 Views Asked by At

Hi I instantiated an isolate for my data layer above my main app, above runApp()

I wonder what will happen when the app is minimised, will the isolate be closed. Do isolates time out anyway...

Has anyone got experience of this in a live app?

2

There are 2 best solutions below

1
On

As from Flutter's happy recommendeations page:

There are a of couple ways to incorporate background processing into your mobile app. One way is through a Dart isolate. With a Dart isolate, you can create a separate thread to run tasks concurrently in the background.

Another way to incorporate background processing is through the WorkManager plugin. With this plugin, you can enable persistent headless execution of Dart code. Your tasks remain scheduled through app restarts and system reboots.

so the answer is yes, you can achieve running dart code in the background with Dart isolates, but consider also using the workManager package.

0
On

I tested the situation proposed, and the isolates were working(simply setup a timer which logs some random message to console) even if app is minimised. If the app is killed by user or by OS, isolates will be killed as well. And yes you can spawn an isolate before runApp(). If the isolate is required to return some data to the main isolate, I recommend making the main() function async and wait(await) for the completion. Flutter will not render the UI until everything before runApp() is completed without error.