一個用於 workmanager 插件的共享平台介面,可於 Android、iOS、Linux、macOS、Web 與 Windows 上實現一致的背景任務執行。它抽象了平台特定的實作,讓開發者能撰寫可靠且跨平台的程式碼,以排程與管理背景工作。該介面確保相容性,並透過統一的 API 簡化與原生平台的整合。此套件是 workmanager 生態系統的基礎,支援週期性任務與一次性作業等功能。
適用情境
在多個平台排程背景任務
在背景中執行定時作業
執行一次性背景作業
確保跨平台一致性
支援長時間執行的背景流程
主要特色
跨平台統一 API
平台抽象層
支援 Android、iOS、Linux、macOS、Web 與 Windows
啟用背景任務排程
促進外掛程式可擴充性
適合對象
使用背景任務開發跨平台應用的開發者
需要一致的後台作業管理的團隊
使用 workmanager 插件生態系統的專案
需要可靠週期性或一次性背景執行的應用程式
使用建議
需要由平台特定的外掛程式實作
沒有具體的平台實現,無法獨立使用
依賴主 workmanager 包以實現功能
在某些平台可能需要額外權限
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
Flutter Workmanager
Execute Dart code in the background, even when your app is closed (Android and iOS). On macOS, background tasks run while the app is running or backgrounded and the Mac is awake. Perfect for data sync, file uploads, and periodic maintenance tasks.
⚠️ Experimental web support now exists via workmanager_web (Service
Worker + Web Worker based background execution). See the
Web (experimental) page and the
package README for honest limitations and how to
test it in Chrome.
→ Troubleshooting Guide - Why tasks stop after app close (OEM battery optimization, constraints, verification)
🎯 Use Cases
Background tasks are perfect for:
Sync data from API - Keep your app's data fresh
Upload files in background - Reliable file uploads
Clean up old data - Remove old files and cache
Fetch notifications - Check for new messages
Database maintenance - Optimize and clean databases
⏱ Long-Running Tasks (Android)
For work that takes longer than the regular background execution window (bulk
uploads/downloads, ML processing), Android tasks can run as a foreground
service with a persistent notification. Pass a foregroundServiceConfig to
registerOneOffTask or registerPeriodicTask:
awaitWorkmanager().registerOneOffTask(
"upload-task",
"upload_files",
foregroundServiceConfig: ForegroundServiceConfig(
notificationTitle: "Uploading files",
notificationText: "Your files are being uploaded",
),
);
cancelByUniqueName, cancelByTag and cancelAll stop the WorkManager worker
immediately, but the Dart callback that is currently running keeps executing
unless it reacts to the stop. Pass an onTaskStopped handler to executeTask
inside your callbackDispatcher to be notified when a running task is stopped
before it finishes:
@pragma('vm:entry-point')
voidcallbackDispatcher() {
Workmanager().executeTask(
(taskName, inputData) async {
returntrue;
},
onTaskStopped: (taskName, stopReason) async {
// Mark the task as cancelled / persist state, then return promptly.
},
);
}
The handler receives the task name and the WorkManager stop reason
(cancelledByApp, timeout, preempt, ...); on Android < 12 the reason is
StopReason.unknown. Android-only — iOS has no way to stop a running task.
See the Customization guide
for details.