Mobile Development8 min read
Flutter Workmanager: Background Tasks
Run reliable Flutter background tasks with Workmanager: one-off and periodic jobs, constraints, retries and iOS limits, with complete working Dart code.
- #flutter
- #workmanager
- #background-tasks
- #android
- #ios

A Flutter app stops executing Dart code when the operating system suspends or kills its process, so a timer inside the app cannot sync data, upload a file, or refresh a cache while the app is closed. Workmanager solves that problem by handing the job to the operating system scheduler, which wakes the app later under conditions the developer declares. This guide builds a complete background sync task with the workmanager package: initialization, a one-off upload, a periodic refresh, constraints, retry policy, and the iOS limits that shape the design. Background work pairs naturally with two related patterns. Heavy computation that only needs to avoid jank belongs in an isolate, covered in Flutter Isolates: Heavy Work Without Jank. User-facing reminders belong in Flutter Local Notifications: Full Guide. Workmanager covers the remaining case: deferrable work that must survive the app process ending.
What is Workmanager in Flutter?
Workmanager is a Flutter plugin that wraps Android WorkManager and iOS BGTaskScheduler behind one Dart API for deferrable, guaranteed background work. A developer registers a task with a unique name, a Dart callback, and optional constraints such as network availability or charging state. The operating system stores the request persistently, so the task survives process death and device restarts, and runs the callback when the constraints are satisfied. Workmanager is the right tool for uploads, downloads, data sync, cache cleanup, and periodic refresh. Use Workmanager when the work is deferrable and must eventually happen, not when it must happen at an exact second. Android WorkManager batches jobs to save battery, so a periodic task runs near its interval rather than precisely on it. Exact alarms need a different mechanism, as described in Flutter Exact Alarm Scheduling on Android. The official Flutter guide on background processes explains how the framework starts a headless engine for this kind of work.
How do you set up Workmanager?
Set up Workmanager by adding the workmanager package, writing a top-level callback dispatcher marked as an entry point, and initializing the plugin before runApp. The callback runs in a separate background isolate with no access to the widget tree or to state held in the main isolate, so the callback must initialize its own dependencies, such as a database connection or an HTTP client. The entry point annotation prevents the Dart compiler from tree-shaking the function away in release builds.
dependencies:
workmanager: ^0.6.0
import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
const syncTaskName = 'syncPendingUploads';
const refreshTaskName = 'periodicCacheRefresh';
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) async {
switch (taskName) {
case syncTaskName:
final userId = inputData?['userId'] as String? ?? '';
return syncPendingUploads(userId);
case refreshTaskName:
return refreshCache();
default:
return Future.value(true);
}
});
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Workmanager().initialize(
callbackDispatcher,
isInDebugMode: false,
);
runApp(const MyApp());
}
The executeTask callback returns a Future of bool. Returning true marks the task as successful. Returning false marks it as failed and, when a backoff policy is set, schedules a retry. Throwing an uncaught error also counts as failure, but an explicit false is clearer and keeps the retry decision in the developer's hands.
How do you register a one-off background task?
Register a one-off background task with registerOneOffTask, giving it a unique name, the task name the callback switches on, and constraints that describe when the work may run. The unique name identifies the registration so a later call can replace, keep, or append to the existing request through the existing work policy. Input data passes small, serializable values such as an ID; large payloads belong in a database or file that the callback reads.
Future<void> scheduleUploadSync(String userId) async {
await Workmanager().registerOneOffTask(
'upload-sync-$userId',
syncTaskName,
inputData: {'userId': userId},
constraints: Constraints(
networkType: NetworkType.connected,
requiresBatteryNotLow: true,
),
backoffPolicy: BackoffPolicy.exponential,
backoffPolicyDelay: const Duration(minutes: 1),
existingWorkPolicy: ExistingWorkPolicy.replace,
);
}
The sync function itself does the real work and reports success honestly:
Future<bool> syncPendingUploads(String userId) async {
try {
final pending = await UploadQueue.readPending(userId);
for (final item in pending) {
final ok = await ApiClient.upload(item);
if (!ok) return false;
await UploadQueue.markDone(item.id);
}
return true;
} catch (_) {
return false;
}
}
Returning false on the first failed item keeps the queue ordered and lets the exponential backoff space out retries instead of hammering a failing server.
How do periodic tasks work in Workmanager?
Periodic tasks in Workmanager repeat on an interval with a minimum period of 15 minutes on Android, and the system may run them later than the interval to batch work and save battery. Register one with registerPeriodicTask, set the frequency, and add constraints so the refresh only runs when it can succeed. A periodic task is ideal for refreshing a cache, pruning old files, or checking for new content a few times a day.
Future<void> scheduleCacheRefresh() async {
await Workmanager().registerPeriodicTask(
'cache-refresh',
refreshTaskName,
frequency: const Duration(hours: 6),
constraints: Constraints(
networkType: NetworkType.connected,
requiresCharging: false,
),
existingWorkPolicy: ExistingWorkPolicy.keep,
);
}
The keep policy matters here: registering the same periodic task on every app launch with replace would reset its schedule each time and could starve it. Keep leaves an existing registration untouched, so the task keeps its original cadence.
| Task type | Registration call | Minimum timing | Best use |
|---|---|---|---|
| One-off | registerOneOffTask | Runs when constraints allow | Uploads, downloads, single syncs |
| Periodic | registerPeriodicTask | 15 minutes on Android | Cache refresh, cleanup, polling |
| One-off with delay | registerOneOffTask with initialDelay | After the delay, constraints permitting | Retry later, deferred reminders |
Which constraints and retry policies should you use?
Constraints in Workmanager declare the conditions a task needs, and the system delays execution until every condition holds. NetworkType.connected requires any network, NetworkType.unmetered requires Wi-Fi-like connectivity for large transfers, requiresCharging waits for a charger, and requiresBatteryNotLow avoids draining a nearly empty battery. Matching constraints to the cost of the work is the main lever for battery-friendly background behavior.
| Constraint | Effect | Typical choice |
|---|---|---|
| NetworkType.connected | Any working network | Small syncs and API calls |
| NetworkType.unmetered | Unmetered network only | Large uploads and downloads |
| requiresCharging | Device plugged in | Heavy processing, big batches |
| requiresBatteryNotLow | Battery above the low threshold | Most deferrable work |
| requiresDeviceIdle | Device idle | Maintenance and cleanup |
| Retry behavior comes from the backoff policy. BackoffPolicy.exponential doubles the delay after each failure, starting from backoffPolicyDelay, which suits network failures that need time to clear. BackoffPolicy.linear adds a fixed step each time. A task that keeps failing is retried until it succeeds or is cancelled, so the callback should distinguish permanent failures, such as a rejected payload, from transient ones, and return true after recording a permanent failure to stop pointless retries. |
What are the iOS limits for Workmanager?
Workmanager on iOS uses BGTaskScheduler, which gives the system full control over timing: iOS decides when, and whether, a background task runs based on usage patterns, battery, and connectivity. The plugin supports two iOS task kinds, a short app-refresh task and a longer processing task, and each identifier must be declared in the Info.plist under BGTaskSchedulerPermittedIdentifiers and registered in the AppDelegate before the app finishes launching. Periodic work on iOS is best-effort, never a schedule the app can rely on for correctness. Two practical rules follow from the iOS model. First, keep each background run short and resumable: save progress as the work proceeds, because the system can stop the task when its time budget expires. Second, treat background execution as an optimization, not a requirement: the app must still sync correctly on launch if no background run ever happened. Designing the sync to be idempotent, so running it twice changes nothing, makes both platforms behave predictably.
How do you test and debug background tasks?
Test background tasks by setting isInDebugMode to true during development, which makes the plugin log task execution, and by triggering a one-off task with no constraints so it runs promptly. On Android, the WorkManager inspector in Android Studio shows enqueued, running, and finished work, which confirms whether a registration exists and which constraints are holding it. On iOS, background tasks can be simulated from the Xcode debugger, because real BGTaskScheduler runs depend on system conditions that a test device may not reproduce on demand. Three failure modes account for most background task bugs. A callback that is not top-level, or that lacks the entry point annotation, never runs in release builds. A callback that assumes main-isolate state, such as an already-open database singleton, fails because the background isolate starts fresh. A periodic task re-registered with replace on every launch keeps resetting its own schedule. Checking those three points first resolves the majority of reports that a task never fired.
Conclusion
Workmanager turns deferrable background work into a system-managed guarantee: register a task with constraints and a retry policy, keep the callback self-contained and idempotent, and let Android WorkManager and iOS BGTaskScheduler decide the exact moment. Design for the iOS reality that timing is best-effort, and the same code stays reliable on both platforms. Building an app that needs dependable uploads, offline sync, or scheduled background work? Get in touch and let's talk about your project.
Frequently asked questions
- What is Workmanager in Flutter?
- Workmanager is a Flutter plugin that wraps Android WorkManager and iOS BGTaskScheduler behind one Dart API. A developer registers a task with a unique name, a Dart callback, and constraints, and the operating system runs the callback later even if the app process has ended.
- Why does my Workmanager task never run?
- The most common causes are a callback that is not top-level or lacks the vm entry point annotation, a callback that assumes state from the main isolate, and a periodic task re-registered with the replace policy on every launch. Constraints that are never satisfied, such as requiring an unmetered network, also hold a task indefinitely.
- How often can a periodic Workmanager task run?
- On Android the minimum period for a periodic Workmanager task is 15 minutes, and the system may run it later than the interval to batch work and save battery. On iOS, BGTaskScheduler decides timing entirely, so periodic execution is best-effort rather than scheduled.
- Does Workmanager work when the app is killed?
- Yes. Android WorkManager and iOS BGTaskScheduler store task requests persistently, so registered work survives the app process ending and device restarts. The system starts a background isolate to run the callback when the task constraints are satisfied.


