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.