workmanager_apple 套件為 workmanager 插件提供 Apple 平台(iOS 與 macOS)支援,讓 Flutter 應用程式能在背景執行任務。它允許開發者排程週期性或單次任務,即使應用程式終止也能執行,確保在 Apple 設備上可靠地進行背景處理。此實作與 iOS 與 macOS 系統 API 整合,有效管理背景執行,同時尊重平台特定的限制與省電功能。
適用情境
計劃定期數據同步
後台位置更新正在執行
執行延遲通知
執行離線數據處理
保持後台任務連續性
主要特色
Apple 平台特定的後台任務處理
與 iOS/macOS 系統 API 的整合
支援週期性與一次性任務
省電的背景執行
與 workmanager core 的無縫整合
適合對象
Flutter 應用在 iOS 上需要背景處理
針對 macOS 且有背景需求的開發者
需要可靠後台任務排程的應用
跨平台使用 workmanager 插件的項目
具有資料同步或監控需求的應用程式
使用建議
需要在 Xcode 專案設定中進行正確設定
iOS 上的背景執行時間有限
必須在應用功能中啟用背景模式
不適用於所有後台工作類型
某些操作可能需要使用者權限
原始 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.