events property
Stream of task completion events.
Recommended: Use this stream to reactively respond to task completions instead of polling getTaskStatus.
Example - Show Notification on Completion
@override
void initState() {
super.initState();
// Listen to task events
NativeWorkManager.events.listen((event) {
if (event.success) {
showNotification(
title: 'Task Complete',
body: 'Task ${event.taskId} finished successfully',
);
} else {
showError(
title: 'Task Failed',
body: event.message ?? 'Unknown error',
);
}
});
}
Example - Update UI on Upload Complete
class UploadManager {
StreamSubscription? _eventSub;
void startListening() {
_eventSub = NativeWorkManager.events.listen((event) {
if (event.taskId.startsWith('upload-')) {
if (event.success) {
markUploadComplete(event.taskId);
refreshUI();
} else {
showRetryDialog(event.taskId);
}
}
});
}
void dispose() {
_eventSub?.cancel();
}
}
Example - Collect Statistics
int successCount = 0;
int failureCount = 0;
NativeWorkManager.events.listen((event) {
if (event.success) {
successCount++;
} else {
failureCount++;
}
print('Success: $successCount, Failed: $failureCount');
});
Event Properties
Each TaskEvent contains:
taskId- ID of the completed tasksuccess- true if task succeeded, false if failedmessage- Optional error message (only present on failure)
Behavior
- Emits an event when ANY task completes (success or failure)
- Events are emitted even if app is in background
- Stream is broadcast - multiple listeners supported
- Events are NOT persisted - you won't receive events for tasks that completed while app was closed
Platform Notes
Android:
- Events delivered via EventChannel
- Immediate delivery when app is running
iOS:
- Events delivered when app comes to foreground
- May be batched if multiple tasks completed while app was suspended
Common Patterns
Filter by task ID prefix:
NativeWorkManager.events
.where((event) => event.taskId.startsWith('sync-'))
.listen((event) {
// Only sync tasks
});
Handle only failures:
NativeWorkManager.events
.where((event) => !event.success)
.listen((event) {
logError('Task ${event.taskId} failed: ${event.message}');
});
Common Pitfalls
❌ Don't forget to cancel subscriptions (causes memory leaks) ❌ Don't perform heavy work in listener (blocks event stream) ✅ Do use StreamBuilder for UI updates ✅ Do filter events by taskId prefix for organization
See Also
- progress - Stream of progress updates during task execution
- getTaskStatus - Query task status on-demand
Implementation
static Stream<TaskEvent> get events {
_checkInitialized();
return NativeWorkManagerPlatform.instance.events;
}