|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:flutter/cupertino.dart'; |
| 4 | +import 'package:injectable/injectable.dart'; |
| 5 | +import 'package:stream_feeds/stream_feeds.dart'; |
| 6 | + |
| 7 | +@LazySingleton(as: LifecycleStateProvider) |
| 8 | +class AppLifecycleStateProvider |
| 9 | + with Disposable, WidgetsBindingObserver |
| 10 | + implements LifecycleStateProvider { |
| 11 | + AppLifecycleStateProvider() { |
| 12 | + // Start listening to lifecycle changes. |
| 13 | + WidgetsBinding.instance.addObserver(this); |
| 14 | + } |
| 15 | + |
| 16 | + @override |
| 17 | + LifecycleStateEmitter get state => _state; |
| 18 | + late final _state = MutableStateEmitter(LifecycleState.foreground); |
| 19 | + |
| 20 | + @override |
| 21 | + void didChangeAppLifecycleState(AppLifecycleState state) { |
| 22 | + final wasInBackground = _state.value == LifecycleState.background; |
| 23 | + final isInBackground = !_isAppInForeground(state); |
| 24 | + |
| 25 | + if (wasInBackground && !isInBackground) { |
| 26 | + _state.value = LifecycleState.foreground; |
| 27 | + } else if (!wasInBackground && isInBackground) { |
| 28 | + _state.value = LifecycleState.background; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + bool _isAppInForeground(AppLifecycleState state) { |
| 33 | + return switch (state) { |
| 34 | + AppLifecycleState.resumed || AppLifecycleState.inactive => true, |
| 35 | + _ => false, |
| 36 | + }; |
| 37 | + } |
| 38 | + |
| 39 | + @override |
| 40 | + Future<void> dispose() async { |
| 41 | + await _state.close(); |
| 42 | + WidgetsBinding.instance.removeObserver(this); |
| 43 | + return super.dispose(); |
| 44 | + } |
| 45 | +} |
0 commit comments