Complete API documentation for native_workmanager v1.2.2
Main entry point for scheduling and managing background tasks.
Initializes the work manager. Must be called before any other methods.
static Future<void> initialize({
Map<String, DartWorkerCallback>? dartWorkers,
bool debugMode = false,
int maxConcurrentTasks = 4,
int diskSpaceBufferMB = 20,
int cleanupAfterDays = 30,
bool enforceHttps = false,
bool blockPrivateIPs = false,
bool registerPlugins = false,
})Parameters:
dartWorkers- Optional map ofDartWorkerCallbackfor executing Dart code in the background.debugMode- Enable verbose logging (defaults tofalse).maxConcurrentTasks- Maximum number of background tasks running simultaneously (defaults to 4).diskSpaceBufferMB- Required free disk space before I/O tasks run (defaults to 20MB).cleanupAfterDays- Days to keep completed task records in SQLite (defaults to 30, use 0 to disable).enforceHttps- When true, all HTTP workers reject plain HTTP URLs (defaults tofalse).blockPrivateIPs- When true, HTTP workers reject requests to private IP ranges to prevent SSRF (defaults tofalse).registerPlugins- When true, registers all plugins in the background Flutter Engine. Defaults tofalseto maintain the Zero-Engine I/O principle.- Caution: Enabling this increases RAM usage and may cause hardware side-effects (e.g., Bluetooth disconnects).
- Recommendation: Keep this
falseand usesetPluginRegistrantCallbackon the native side for selective registration.
Example:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await NativeWorkManager.initialize();
runApp(MyApp());
}Schedules a single background task.
static Future<void> enqueue({
required String taskId,
required TaskTrigger trigger,
required Worker worker,
Constraints? constraints,
Map<String, dynamic>? inputData,
})Parameters:
taskId- Unique identifier for the tasktrigger- When/how the task should run (one-time, periodic, etc.)worker- The worker that executes the task logicconstraints- Optional execution constraints (network, battery, etc.)inputData- Optional input data passed to worker
Example:
await NativeWorkManager.enqueue(
taskId: 'api-sync',
trigger: TaskTrigger.periodic(Duration(hours: 1)),
worker: NativeWorker.httpSync(
url: 'https://api.example.com/sync',
),
constraints: Constraints(requiresNetwork: true),
);Creates a task chain for sequential or parallel execution.
static TaskChainBuilder beginWith(TaskRequest firstTask)Returns: TaskChainBuilder for chaining more tasks
Example:
await NativeWorkManager.beginWith(
TaskRequest(id: 'download', worker: HttpDownloadWorker(...)),
).then(
TaskRequest(id: 'process', worker: ImageProcessWorker(...)),
).then(
TaskRequest(id: 'upload', worker: HttpUploadWorker(...)),
).enqueue();Cancels a scheduled task by ID.
static Future<void> cancel(String taskId)Example:
await NativeWorkManager.cancel('api-sync');Cancels all scheduled tasks.
static Future<void> cancelAll()Example:
await NativeWorkManager.cancelAll();Stream of task completion events.
static Stream<TaskEvent> get eventsReturns: Stream emitting TaskEvent for each completed task
Example:
NativeWorkManager.events.listen((event) {
print('Task ${event.taskId}: ${event.success ? "✅" : "❌"}');
print('Message: ${event.message}');
});Factory for creating built-in native workers (no Flutter engine overhead).
Simple HTTP request worker.
static Worker httpRequest({
required String url,
HttpMethod method = HttpMethod.get,
Map<String, String> headers = const {},
String? body,
Duration timeout = const Duration(seconds: 30),
TokenRefreshConfig? tokenRefresh,
})Multipart file upload worker.
static Worker httpUpload({
required String url,
required String filePath,
String fileFieldName = 'file',
String? fileName,
String? mimeType,
Map<String, String> headers = const {},
Map<String, String> additionalFields = const {},
Duration timeout = const Duration(minutes: 5),
bool useBackgroundSession = false,
})File download worker with resume support.
static Worker httpDownload({
required String url,
required String savePath,
Map<String, String> headers = const {},
Duration timeout = const Duration(minutes: 5),
bool enableResume = true,
String? expectedChecksum,
String checksumAlgorithm = 'SHA-256',
bool useBackgroundSession = false,
bool skipExisting = false,
bool allowPause = false,
Map<String, String>? cookies,
String? authToken,
String authHeaderTemplate = 'Bearer {accessToken}',
DuplicatePolicy onDuplicate = DuplicatePolicy.overwrite,
bool moveToPublicDownloads = false,
bool saveToGallery = false,
})Bidirectional sync worker with retry.
static Worker httpSync({
required String url,
HttpMethod method = HttpMethod.post,
Map<String, String> headers = const {},
Map<String, dynamic>? requestBody,
Duration timeout = const Duration(seconds: 60),
TokenRefreshConfig? tokenRefresh,
})Compress files/directories to ZIP.
static Worker fileCompress({
required String inputPath,
required String outputPath,
CompressionLevel level = CompressionLevel.medium,
List<String> excludePatterns = const [],
bool deleteOriginal = false,
})Extract ZIP archives.
static Worker fileDecompress({
required String zipPath,
required String targetDir,
bool deleteAfterExtract = false,
bool overwrite = true,
})Copy files or directories.
static Worker fileCopy({
required String sourcePath,
required String destinationPath,
bool overwrite = false,
bool recursive = true,
})Move files or directories.
static Worker fileMove({
required String sourcePath,
required String destinationPath,
bool overwrite = false,
})Delete files or directories.
static Worker fileDelete({
required String path,
bool recursive = false,
})List files in directory with pattern matching.
static Worker fileList({
required String path,
String? pattern,
bool recursive = false,
})Create directory.
static Worker fileMkdir({
required String path,
bool createParents = true,
})Process images (resize, compress, convert).
static Worker imageProcess({
required String inputPath,
required String outputPath,
int? maxWidth,
int? maxHeight,
bool maintainAspectRatio = true,
int? quality,
ImageFormat? outputFormat,
ImageCropRect? cropRect,
bool deleteOriginal = false,
})Calculate file hash.
static Worker hashFile({
required String filePath,
HashAlgorithm algorithm = HashAlgorithm.sha256,
})Calculate string hash.
static Worker hashString({
required String data,
HashAlgorithm algorithm = HashAlgorithm.sha256,
})Encrypt file with AES-256-GCM.
static Worker cryptoEncrypt({
required String inputPath,
required String outputPath,
required String password,
})Decrypt AES-256-GCM encrypted file.
static Worker cryptoDecrypt({
required String inputPath,
required String outputPath,
required String password,
})Worker for custom Dart logic (uses Flutter engine).
DartWorker({
required String callbackId,
Map<String, dynamic>? input,
bool autoDispose = false,
int? timeoutMs,
})Parameters:
callbackId- Identifier for registered callback functioninput- Optional data passed to callbackautoDispose- Whether to dispose Flutter engine after execution (default:false)timeoutMs- Optional execution timeout in milliseconds
Example:
// Register callback (in main.dart during initialize)
@WorkerCallback('processData')
Future<bool> myProcessData(String? inputData) async {
// Your Dart logic here
print('Processing data...');
return true;
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await NativeWorkManager.initialize(
dartWorkers: {
'processData': myProcessData,
}
);
runApp(MyApp());
}
// Schedule task
await NativeWorkManager.enqueue(
taskId: 'process',
trigger: TaskTrigger.oneTime(),
worker: DartWorker(callbackId: 'processData'),
);Defines when tasks should execute.
Execute task once after optional delay.
static TaskTrigger oneTime([Duration? initialDelay])Example:
TaskTrigger.oneTime(Duration(seconds: 30)) // Run after 30 secondsExecute task repeatedly at fixed interval.
static TaskTrigger periodic(Duration interval)Example:
TaskTrigger.periodic(Duration(hours: 1)) // Run every hourNote: Minimum interval is 15 minutes on both iOS and Android.
Execute when device is idle (Android only).
static TaskTrigger deviceIdle()Execute when battery is not low.
static TaskTrigger batteryOkay()Execution constraints for tasks.
Constraints({
bool requiresNetwork = false,
bool requiresUnmeteredNetwork = false,
bool requiresCharging = false,
bool requiresBatteryNotLow = false,
bool requiresStorageNotLow = false,
bool requiresDeviceIdle = false,
BackoffPolicy backoffPolicy = BackoffPolicy.exponential,
int backoffDelayMs = 30000,
int maxAttempts = 3,
bool isHeavyTask = false,
})Example:
Constraints(
requiresNetwork: true,
requiresUnmeteredNetwork: true, // WiFi only
requiresCharging: true,
backoffPolicy: BackoffPolicy.exponential,
maxAttempts: 5,
)enum HttpMethod {
get,
post,
put,
delete,
patch,
}enum CompressionLevel {
low,
medium,
high,
}enum ImageFormat {
jpeg,
png,
webp,
}enum HashAlgorithm {
md5,
sha1,
sha256,
sha512,
}enum BackoffPolicy {
linear,
exponential,
}Emitted when task completes.
class TaskEvent {
final String taskId;
final bool success;
final String? message;
final DateTime timestamp;
final Map<String, dynamic>? outputData;
}Example:
NativeWorkManager.events.listen((event) {
if (event.success) {
print('✅ ${event.taskId} completed: ${event.message}');
} else {
print('❌ ${event.taskId} failed: ${event.message}');
}
});Builder for creating task chains.
Add sequential task.
TaskChainBuilder then(TaskRequest task)Add parallel tasks.
TaskChainBuilder thenAll(List<TaskRequest> tasks)Schedule the chain.
Future<void> enqueue()Represents a task in a chain.
TaskRequest({
required String id,
required Worker worker,
Constraints? constraints,
Map<String, dynamic>? inputData,
})For large file transfers that survive app termination.
// Use with httpDownload or httpUpload
NativeWorker.httpDownload(
url: 'https://example.com/large-file.zip',
savePath: '/path/to/save.zip',
useBackgroundSession: true, // ← iOS Background URLSession
)Benefits:
- Survives app termination
- No time limits
- Automatic retry on network failure
Version: 1.2.2 Last Updated: 2026-04-20