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.