app_lifecycle.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2022, the Flutter project authors. Please see the AUTHORS file
  2. // for details. All rights reserved. Use of this source code is governed by a
  3. // BSD-style license that can be found in the LICENSE file.
  4. import 'package:flutter/widgets.dart';
  5. import 'package:logging/logging.dart';
  6. import 'package:provider/provider.dart';
  7. class AppLifecycleObserver extends StatefulWidget {
  8. final Widget child;
  9. const AppLifecycleObserver({required this.child, super.key});
  10. @override
  11. State<AppLifecycleObserver> createState() => _AppLifecycleObserverState();
  12. }
  13. class _AppLifecycleObserverState extends State<AppLifecycleObserver> with WidgetsBindingObserver {
  14. static final _log = Logger('AppLifecycleObserver');
  15. final ValueNotifier<AppLifecycleState> lifecycleListenable = ValueNotifier(AppLifecycleState.resumed); // default set to AppLifecycleState.resumed
  16. @override
  17. Widget build(BuildContext context) {
  18. // Using InheritedProvider because we don't want to use Consumer
  19. // or context.watch or anything like that to listen to this. We want
  20. // to manually add listeners. We're interested in the _events_ of lifecycle
  21. // state changes, and not so much in the state itself. (For example,
  22. // we want to stop sound when the app goes into the background, and
  23. // restart sound again when the app goes back into focus. We're not
  24. // rebuilding any widgets.)
  25. //
  26. // Provider, by default, throws when one
  27. // is trying to provide a Listenable (such as ValueNotifier) without using
  28. // something like ValueListenableProvider. InheritedProvider is more
  29. // low-level and doesn't have this problem.
  30. return InheritedProvider<ValueNotifier<AppLifecycleState>>.value(value: lifecycleListenable, child: widget.child);
  31. }
  32. @override
  33. void didChangeAppLifecycleState(AppLifecycleState state) {
  34. _log.info(() => 'didChangeAppLifecycleState: $state');
  35. lifecycleListenable.value = state;
  36. }
  37. @override
  38. void didHaveMemoryPressure() {
  39. _log.warning(() => 'didHaveMemoryPressure');
  40. // FirebaseCrashlytics.instance.log("didHaveMemoryPressure");
  41. }
  42. @override
  43. void dispose() {
  44. WidgetsBinding.instance.removeObserver(this);
  45. super.dispose();
  46. }
  47. @override
  48. void initState() {
  49. super.initState();
  50. WidgetsBinding.instance.addObserver(this);
  51. _log.info('Subscribed to app lifecycle updates');
  52. }
  53. }