Flutter App State Manager

Enhanced app lifecycle management with background task handling for Flutter applications.

Pub Version License Flutter

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 events
  • BackgroundTaskManager - Handles background task execution and scheduling
  • StateManager<T> - Generic state management with reactive streams
  • BackgroundTask<T> - Abstract base class for background tasks

Enums

  • AppLifecycleState - Application lifecycle states
  • TaskPriority - Background task priority levels
  • TaskStatus - Background task execution status

Events

  • LifecycleEvent - Lifecycle state change events
  • StateChangeEvent<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:

  1. Check the issue tracker
  2. Create a new issue with detailed information
  3. Contact the maintainer

Made with ❀️ by Dhia Bechattaoui

Libraries

flutter_app_state_manager
Enhanced app lifecycle management with background task handling for Flutter applications.