Flutter App State Manager
Enhanced app lifecycle management with background task handling for Flutter applications.
Features
- π Enhanced App Lifecycle Management - Comprehensive lifecycle state tracking and event handling
- π Background Task Management - Efficient background task execution and scheduling
- π± Cross-Platform Support - Works on iOS, Android, Web, Windows, macOS, and Linux
- π Web Optimized - Full support for Flutter web applications
- π― Generic State Management - Flexible state management with reactive streams
- β‘ Performance Optimized - Memory-efficient with thread-safe operations
- π‘οΈ Null Safety - Full null safety support
- π Comprehensive Testing - Extensive unit test coverage
Getting Started
Installation
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_app_state_manager: ^0.0.1
Basic Usage
App Lifecycle Management
import 'package:flutter_app_state_manager/flutter_app_state_manager.dart';
void main() {
// Initialize the lifecycle manager
final lifecycleManager = AppLifecycleManager.instance;
lifecycleManager.initialize();
// Listen to lifecycle events
lifecycleManager.addListener((event) {
print('App state changed to: ${event.state}');
});
// Listen to specific state changes
lifecycleManager.onForeground.listen((event) {
print('App entered foreground');
});
lifecycleManager.onBackground.listen((event) {
print('App entered background');
});
}
State Management
// Create a state manager for any type
final counterState = StateManager<int>(0);
// Listen to state changes
counterState.addListener((oldValue, newValue) {
print('Counter changed from $oldValue to $newValue');
});
// Update state
counterState.updateState(5);
// Transform state
counterState.updateStateWith((current) => current + 1);
// Stream-based access
counterState.stateStream.listen((value) {
print('Current counter value: $value');
});
Background Task Management
// Create a background task
final task = SimpleBackgroundTask<String>(
id: 'data_fetch',
name: 'Fetch Data from API',
executor: () async {
// Simulate API call
await Future.delayed(Duration(seconds: 2));
return 'Data fetched successfully';
},
);
// Register and execute the task
final taskManager = BackgroundTaskManager.instance;
taskManager.registerTask(task);
// Execute immediately
final result = await taskManager.executeTask('data_fetch');
if (result.success) {
print('Task completed: ${result.data}');
} else {
print('Task failed: ${result.errorMessage}');
}
// Schedule for later
taskManager.scheduleTask('data_fetch', Duration(minutes: 5));
Advanced Usage
Custom Background Tasks
class CustomBackgroundTask extends BackgroundTask<String> {
CustomBackgroundTask({
required super.id,
required super.name,
super.priority = TaskPriority.high,
});
@override
Future<TaskResult<String>> execute() async {
try {
// Your custom logic here
final result = await performComplexOperation();
return TaskResult.success(result);
} catch (e) {
return TaskResult.failure(e.toString(), errorDetails: e);
}
}
@override
Future<bool> cancel() async {
// Implement cancellation logic
return true;
}
}
State Management with Mixins
class MyController with StateManageable<int> {
@override
int get initialState => 0;
void increment() {
updateStateWith((current) => current + 1);
}
void decrement() {
updateStateWith((current) => current - 1);
}
}
Lifecycle-Aware Components
class LifecycleAwareWidget extends StatefulWidget {
@override
_LifecycleAwareWidgetState createState() => _LifecycleAwareWidgetState();
}
class _LifecycleAwareWidgetState extends State<LifecycleAwareWidget> {
late StreamSubscription<LifecycleEvent> _subscription;
@override
void initState() {
super.initState();
final lifecycleManager = AppLifecycleManager.instance;
_subscription = lifecycleManager.lifecycleEvents.listen((event) {
switch (event.state) {
case AppLifecycleState.resumed:
_onResume();
break;
case AppLifecycleState.paused:
_onPause();
break;
default:
break;
}
});
}
void _onResume() {
// Handle app resume
print('Widget resumed');
}
void _onPause() {
// Handle app pause
print('Widget paused');
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
Platform Support
This package supports all Flutter platforms:
- β iOS - Full lifecycle management and background task support
- β Android - Comprehensive background task handling
- β Web - Full web lifecycle management and background task support
- β Windows - Native Windows lifecycle management
- β macOS - Full macOS app lifecycle support
- β Linux - Linux desktop lifecycle management
API Reference
Core Classes
AppLifecycleManager
- Manages application lifecycle eventsBackgroundTaskManager
- Handles background task execution and schedulingStateManager<T>
- Generic state management with reactive streamsBackgroundTask<T>
- Abstract base class for background tasks
Enums
AppLifecycleState
- Application lifecycle statesTaskPriority
- Background task priority levelsTaskStatus
- Background task execution status
Events
LifecycleEvent
- Lifecycle state change eventsStateChangeEvent<T>
- State change events with timestamps
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
If you encounter any issues or have questions, please:
- Check the issue tracker
- Create a new issue with detailed information
- Contact the maintainer
Made with β€οΈ by Dhia Bechattaoui
Libraries
- flutter_app_state_manager
- Enhanced app lifecycle management with background task handling for Flutter applications.