flutter_app_state_manager 0.0.1 copy "flutter_app_state_manager: ^0.0.1" to clipboard
flutter_app_state_manager: ^0.0.1 copied to clipboard

Enhanced app lifecycle management with background task handling for Flutter applications

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app_state_manager/flutter_app_state_manager.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App State Manager Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'App State Manager Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final AppLifecycleManager _lifecycleManager = AppLifecycleManager.instance;
  final BackgroundTaskManager _taskManager = BackgroundTaskManager.instance;
  final StateManager<int> _counterState = StateManager<int>(0);

  String _lifecycleStatus = 'Resumed';
  String _taskStatus = 'No tasks';
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _initializeManagers();
  }

  void _initializeManagers() {
    // Initialize lifecycle manager
    _lifecycleManager.initialize();

    // Listen to lifecycle changes
    _lifecycleManager.addListener((event) {
      setState(() {
        _lifecycleStatus = event.state.toString().split('.').last;
      });
    });

    // Listen to counter state changes
    _counterState.addListener((oldValue, newValue) {
      setState(() {
        _counter = newValue;
      });
    });

    // Register a sample background task
    final sampleTask = SimpleBackgroundTask<String>(
      id: 'sample_task',
      name: 'Sample Background Task',
      executor: () async {
        await Future.delayed(const Duration(seconds: 2));
        return 'Task completed at ${DateTime.now()}';
      },
    );

    _taskManager.registerTask(sampleTask);
  }

  Future<void> _executeBackgroundTask() async {
    setState(() {
      _taskStatus = 'Executing...';
    });

    try {
      final result = await _taskManager.executeTask('sample_task');
      setState(() {
        if (result.success) {
          _taskStatus = 'Success: ${result.data}';
        } else {
          _taskStatus = 'Failed: ${result.errorMessage}';
        }
      });
    } catch (e) {
      setState(() {
        _taskStatus = 'Error: $e';
      });
    }
  }

  void _incrementCounter() {
    _counterState.updateStateWith((current) => current + 1);
  }

  void _decrementCounter() {
    _counterState.updateStateWith((current) => current - 1);
  }

  void _simulateLifecycleChange() {
    final states = [
      AppLifecycleState.resumed,
      AppLifecycleState.paused,
      AppLifecycleState.inactive,
      AppLifecycleState.hidden,
    ];

    final currentIndex = states.indexOf(_lifecycleManager.currentState);
    final nextIndex = (currentIndex + 1) % states.length;

    _lifecycleManager.updateState(states[nextIndex]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'App Lifecycle Status',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('Current State: $_lifecycleStatus'),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _simulateLifecycleChange,
                      child: const Text('Simulate Lifecycle Change'),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'State Management',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('Counter: $_counter'),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        ElevatedButton(
                          onPressed: _decrementCounter,
                          child: const Text('-'),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _incrementCounter,
                          child: const Text('+'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Background Task Management',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('Status: $_taskStatus'),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _executeBackgroundTask,
                      child: const Text('Execute Background Task'),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _counterState.dispose();
    super.dispose();
  }
}
2
likes
160
points
38
downloads

Publisher

verified publisherbechattaoui.dev

Weekly Downloads

Enhanced app lifecycle management with background task handling for Flutter applications

Repository (GitHub)
View/report issues

Documentation

Documentation
API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on flutter_app_state_manager