workmanager_web 為 workmanager 包提供了一個實驗性的 Web 實現,允許在 Flutter Web 應用中使用 Service Workers 和 Web Workers 執行背景任務。它可以在應用未積極使用時仍能排程和執行任務,模擬原生的背景處理功能。此套件旨在支援 Web 環境中的週期性和一次性的任務,這些環境傳統上對背景執行有所限制。
適用情境
安排定期的資料同步
應用關閉後執行背景任務
實現推送通知處理
執行長時間運行的操作而不阻塞 UI
支援離線優先的應用程式
主要特色
服務工作者整合
基於 Web Worker 的任務執行
週期性和一次性任務排程
實驗性網路相容性
最小的執行時開銷
適合對象
需要背景任務的 Flutter Web 開發人員
需要定期維護的應用程式
離線可用的網路應用程式
開發人員在網頁上測試後台工作流程
使用建議
實驗性狀態,可能有不穩定性
服務工作者的瀏覽器支援有限
並非所有瀏覽器都能保證執行時間
生產環境需要 HTTPS
不適合用於關鍵的時間敏感操作
原始 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.