BackgroundService class
Manages a generic background service capable of running arbitrary Dart functions.
This service uses a local SQLite database (background_service_jobs
table)
as a job queue. Tasks are enqueued from the main UI isolate and processed
by the background service.
Setup
- Initialize the service: Call BackgroundService.initialize once,
typically in your
main()
function. Provide an AppInitializationCallback. - Implement
AppInitializationCallback
:- Initialize resources needed by background tasks (e.g., database connection for the background isolate, Supabase client).
- Call BackgroundService.setBackgroundDbConnection with the background isolate's database connection.
- Register all job handlers using BackgroundService.registerJobHandler.
- Define Job Handlers: Create functions matching the JobHandler signature for each type of background task.
- Enqueue Jobs: Use BackgroundService.job from your UI isolate to add tasks to the queue.
Android Configuration
Ensure your AndroidManifest.xml
is configured for foreground services as per
the flutter_background_service
plugin documentation. This includes adding
necessary permissions and the service declaration.
iOS Configuration
Follow flutter_background_service
documentation for Info.plist
and
AppDelegate.swift
modifications if background fetch or custom task
identifiers are needed. Note that iOS has limitations on long-running
background tasks.
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
initialize(
{required AppInitializationCallback appInitializationCallback, String initialNotificationTitle = 'Background Service', String initialNotificationContent = 'Processing tasks...', String? notificationIconName}) → Future< void> - Initializes the background service.
-
isRunning(
) → Future< bool> - Checks if the background service is currently running.
-
job(
{required SqliteConnection db, required String jobKey, Map< String, dynamic> ? payload, int priority = 0, int maxAttempts = 3}) → Future<int?> - Enqueues a new job to be processed by the background service.
-
registerJobHandler(
String key, JobHandler handler) → void -
Registers a JobHandler for a specific
jobKey
. -
setBackgroundDbConnection(
SqliteConnection db) → void -
Sets the
SqliteConnection
to be used by the background isolate. -
start(
) → Future< void> -
stop(
) → Future< void> - Stops the background service.