Skip to content

High-performance Flutter background task manager featuring zero-overhead Native Workers (Kotlin/Swift) and Task Chains. Built with Kotlin Multiplatform (KMP) to save 90% RAM & extend battery life.

License

Notifications You must be signed in to change notification settings

brewkits/native_workmanager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

31 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

native_workmanager

Native background task manager for Flutter with zero Flutter Engine overhead.

pub package License: MIT Platform

Flutter background task manager with native workers and task chains.


✨ Key Features

  • Zero Flutter Engine Overhead: Native workers execute I/O tasks without loading the Flutter Engine
  • Task Chains: Automate multi-step workflows (Download β†’ Process β†’ Upload) with built-in dependency management
  • 11 Built-in Workers: HTTP, File operations, Compression, Crypto, Image processing
  • Hybrid Architecture: Choose native workers for I/O or Dart workers for complex logic
  • Production Ready: 808 passing tests, comprehensive documentation, iOS 12.0+ and Android API 21+ support

πŸš€ Quick Start

Step 1: Install

flutter pub add native_workmanager

Step 2: Initialize

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NativeWorkManager.initialize();
  runApp(MyApp());
}

Step 3: Schedule a Task

Option A: Simple HTTP Sync (Native Worker)

// Starts hourly API sync without Flutter Engine overhead
await NativeWorkManager.enqueue(
  taskId: 'sync',
  trigger: TaskTrigger.periodic(Duration(hours: 1)),
  worker: NativeWorker.httpSync(  // ← Native worker
    url: 'https://api.example.com/sync',
    method: HttpMethod.post,
  ),
);
// βœ“ Task runs every hour, even when app is closed
// βœ“ No Flutter Engine overhead

Option B: Complex Dart Logic (Dart Worker)

// For tasks requiring custom Dart code or packages
await NativeWorkManager.enqueue(
  taskId: 'process',
  trigger: TaskTrigger.oneTime(),
  worker: DartWorker(callbackId: 'complexLogic'),  // ← Dart worker
);
// βœ“ Access to all Dart packages
// βœ“ Full Flutter/Dart ecosystem support

Tasks are registered with the OS and survive app restarts, phone reboots, and force-quits.

Complete getting started guide β†’


πŸ”„ Migrating from workmanager?

Good news: ~90% API compatibility, most code stays the same!

Quick Migration Checklist

  • Replace Workmanager.registerPeriodicTask with NativeWorkManager.enqueue
  • Update task trigger syntax (same logic, different API)
  • Replace callback with DartWorker(callbackId) or use native workers
  • Test on both iOS and Android (should work immediately!)

Common Migration Pattern

Before (workmanager):

Workmanager.registerPeriodicTask(
  'myTask',
  'api_sync',
  frequency: Duration(hours: 1),
);

After (native_workmanager):

// Upgrade to native worker
NativeWorkManager.enqueue(
  taskId: 'myTask',
  trigger: TaskTrigger.periodic(Duration(hours: 1)),
  worker: NativeWorker.httpSync(  // ← Native HTTP worker
    url: 'https://api.example.com/sync',
  ),
);

Result: Same functionality, zero Flutter Engine overhead for I/O tasks.

Full migration guide β†’ | Migration tool β†’


🎯 Choose Your Use Case

πŸ“Š I need periodic API sync

β†’ Use Native Workers (zero Flutter Engine overhead)

πŸ“ I need file uploads with retry

β†’ Use HttpUploadWorker with Task Chains

πŸ–ΌοΈ I need photo backup pipeline

β†’ Use Task Chains (Download β†’ Compress β†’ Upload)

  • Sequential or parallel execution
  • Automatic dependency management
  • Failure isolation
  • See example β†’

πŸ”§ I have complex Dart logic

β†’ Use DartWorker with autoDispose

  • Full Flutter Engine access
  • All Dart packages available
  • Smart memory management
  • See example β†’

See all 8 use cases β†’


πŸ’‘ Why native_workmanager?

Unique Features

1. Native Workers

  • Execute I/O tasks without spawning Flutter Engine
  • 11 Built-in Workers: HTTP (request, upload, download, sync), Files (compress, decompress, copy, move, delete), Image processing, Crypto (hash, encrypt, decrypt)
  • Extensible with custom Kotlin/Swift workers

2. Task Chains

  • Automate multi-step workflows: A β†’ B β†’ C or A β†’ [B1, B2, B3] β†’ D
  • Built-in dependency management
  • Automatic retry and failure handling
  • Data passing between steps

3. Hybrid Execution Model

  • Choose per-task: Native workers (I/O) or Dart workers (complex logic)
  • autoDispose flag for fine-grained engine lifecycle control
  • Best of both worlds

4. Cross-Platform Consistency

  • Unified API across Android and iOS
  • Platform feature parity
  • Built on kmpworkmanager for reliability

See FAQ β†’


πŸ–₯️ Platform Support

Platform Status Min Version Key Limitation
Android βœ… Supported API 21 (5.0+) Doze mode may defer tasks
iOS βœ… Supported iOS 12.0+ 30-second execution limit

iOS: 30-Second Execution Limit ⚠️

Background tasks on iOS must complete in 30 seconds. For longer tasks:

Solutions:

  • βœ… Use task chains - Split work into 30-second chunks
  • βœ… Use native workers - Faster than Dart workers (no engine overhead)
  • βœ… Use Background URLSession - For large file transfers (no time limit)
  • ⚠️ Consider foreground services for truly long tasks

Example:

// ❌ Won't work: Takes 90 seconds
await downloadLargeFile();  // 60sec
await processFile();        // 30sec

// βœ… Works: Split into chain (each <30sec)
await NativeWorkManager.beginWith(
  TaskRequest(id: 'download', worker: HttpDownloadWorker(...)),  // 20sec
).then(
  TaskRequest(id: 'process', worker: ImageProcessWorker(...)),   // 15sec
).enqueue();

Read iOS background task guide β†’

Android: Doze Mode & Battery Optimization

Android 6+ may defer tasks in Doze mode. Use constraints to ensure execution:

await NativeWorkManager.enqueue(
  taskId: 'important-sync',
  trigger: TaskTrigger.periodic(Duration(hours: 1)),
  worker: NativeWorker.httpSync(url: 'https://api.example.com/sync'),
  constraints: Constraints(
    requiresNetwork: true,         // Wait for network
    requiresCharging: true,        // Wait for charging (optional)
    requiresBatteryNotLow: true,   // Skip if battery low
  ),
);

Read Android optimization guide β†’


πŸ“š Complete Documentation

πŸš€ Start Here

πŸ“– Learn by Example

πŸ”§ Build It Right

πŸŽ“ Go Deep


❓ FAQ

Q: Will my task run if the app is force-closed? A: Yes! Tasks are registered with the OS (Android WorkManager / iOS BGTaskScheduler), not your Flutter app.

Q: How much memory does a task actually use? A: Native workers execute without Flutter Engine overhead. Dart workers require the full Flutter runtime. Actual memory usage depends on worker type and task complexity.

Q: Can I chain 100 tasks together? A: Yes, but on iOS each task in the chain must complete within 30 seconds. Use native workers for speed.

Q: What happens if a task in a chain fails? A: The chain stops. Subsequent tasks are cancelled. You can use retry policies to handle failures.

Q: Is this compatible with workmanager? A: ~90% compatible. Most code works with minor syntax changes. See migration guide.

Q: Can I use this for location tracking? A: Background tasks are for periodic work, not continuous tracking. For location, use geolocator with background modes.

See full FAQ β†’


πŸ”Œ Popular Integrations

  • Dio - HTTP client for complex requests
  • Hive - Local database sync
  • Firebase - Analytics & Crashlytics
  • Sentry - Error tracking in background tasks

See all integrations β†’


πŸ“Š Production Ready

  • Security: No critical vulnerabilities
  • Tests: 808 unit tests passing
  • Coverage: All 11 native workers tested
  • Platforms: iOS 12.0+ and Android API 21+

🀝 Community & Support

Found a Bug?

  1. Search existing issues
  2. Create new issue with:
    • Flutter version (flutter --version)
    • Platform (iOS/Android)
    • Minimal reproducible example

🀝 Contributing

We welcome contributions! See CONTRIBUTING.md for:

  • How to report bugs
  • How to request features
  • How to submit pull requests
  • Coding standards

πŸ™ Acknowledgments

Built with ❀️ using platform-native APIs:

  • Android: WorkManager - Google's official background task library
  • iOS: BGTaskScheduler - Apple's background task framework
  • Shared Core: kmpworkmanager - Cross-platform worker orchestration

Inspired by Android WorkManager and iOS BackgroundTasks best practices.


πŸ“ž Support & Contact

Need help?

Links:


πŸ“„ License

Licensed under the MIT License - see LICENSE file for details.

Author: Nguyα»…n TuαΊ₯n Việt β€’ BrewKits


⭐ If this library helps your Flutter app, please star the repo!