How do I run code in the background, even with the screen off?

Answering the question of how to implement your specific timer case doesn’t actually have to do with background code. Overall running code in the background is something discouraged on mobile operating systems.

For example, iOS Documentation discusses background code in greater detail here:
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Instead mobile operating systems provide apis (like a timer/alarm/notification apis) to call back to your application after a specific time. For example on iOS you can request that your application be notified/woken at a specific point in the future via UINotificationRequest:
https://developer.apple.com/reference/usernotifications/unnotificationrequest
This allows them to kill/suspend your app to achieve better power savings and instead have a single highly-efficent shared system service for tracking these notifications/alarms/geofencing, etc.

Flutter does not currently provide any wrappers around these OS services out-of-the-box, however it is straighforward to write your own using our platform-services model:
flutter.io/platform-services

We’re working on a system for publishing/sharing service integrations like this so that once one person writes this integration (for say scheduling some future execution of your app) everyone can benefit.

Separately, the more general question of “is it possible to run background Dart code” (without having a FlutterView active on screen), is “not yet”. We have a bug on file:
https://github.com/flutter/flutter/issues/3671 and an open issue: https://github.com/flutter/flutter/issues/32164

The use-case driving that kind of back-ground code execution is when your app receives a notification, wants to process it using some Dart code without bringing your app to the front. If you have other use cases for background code you’d like us to know about, comments are most welcome on that bug!

Leave a Comment