app_lock.dart 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_gen/gen_l10n/app_localizations.dart';
  4. import "package:photos/generated/l10n.dart";
  5. import "package:photos/l10n/l10n.dart";
  6. /// A widget which handles app lifecycle events for showing and hiding a lock screen.
  7. /// This should wrap around a `MyApp` widget (or equivalent).
  8. ///
  9. /// [lockScreen] is a [Widget] which should be a screen for handling login logic and
  10. /// calling `AppLock.of(context).didUnlock();` upon a successful login.
  11. ///
  12. /// [builder] is a [Function] taking an [Object] as its argument and should return a
  13. /// [Widget]. The [Object] argument is provided by the [lockScreen] calling
  14. /// `AppLock.of(context).didUnlock();` with an argument. [Object] can then be injected
  15. /// in to your `MyApp` widget (or equivalent).
  16. ///
  17. /// [enabled] determines wether or not the [lockScreen] should be shown on app launch
  18. /// and subsequent app pauses. This can be changed later on using `AppLock.of(context).enable();`,
  19. /// `AppLock.of(context).disable();` or the convenience method `AppLock.of(context).setEnabled(enabled);`
  20. /// using a bool argument.
  21. ///
  22. /// [backgroundLockLatency] determines how much time is allowed to pass when
  23. /// the app is in the background state before the [lockScreen] widget should be
  24. /// shown upon returning. It defaults to instantly.
  25. ///
  26. // ignore_for_file: unnecessary_this, library_private_types_in_public_api
  27. class AppLock extends StatefulWidget {
  28. final Widget Function(Object?) builder;
  29. final Widget lockScreen;
  30. final bool enabled;
  31. final Duration backgroundLockLatency;
  32. final ThemeData? darkTheme;
  33. final ThemeData? lightTheme;
  34. final ThemeMode savedThemeMode;
  35. final Locale locale;
  36. const AppLock({
  37. Key? key,
  38. required this.builder,
  39. required this.lockScreen,
  40. required this.savedThemeMode,
  41. this.enabled = true,
  42. this.locale = const Locale("en", "US"),
  43. this.backgroundLockLatency = const Duration(seconds: 0),
  44. this.darkTheme,
  45. this.lightTheme,
  46. }) : super(key: key);
  47. static _AppLockState? of(BuildContext context) =>
  48. context.findAncestorStateOfType<_AppLockState>();
  49. @override
  50. State<AppLock> createState() => _AppLockState();
  51. }
  52. class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
  53. static final GlobalKey<NavigatorState> _navigatorKey = GlobalKey();
  54. late bool _didUnlockForAppLaunch;
  55. late bool _isLocked;
  56. late bool _enabled;
  57. Timer? _backgroundLockLatencyTimer;
  58. @override
  59. void initState() {
  60. WidgetsBinding.instance.addObserver(this);
  61. this._didUnlockForAppLaunch = !this.widget.enabled;
  62. this._isLocked = false;
  63. this._enabled = this.widget.enabled;
  64. super.initState();
  65. }
  66. @override
  67. void didChangeAppLifecycleState(AppLifecycleState state) {
  68. if (!this._enabled) {
  69. return;
  70. }
  71. if (state == AppLifecycleState.paused &&
  72. (!this._isLocked && this._didUnlockForAppLaunch)) {
  73. this._backgroundLockLatencyTimer =
  74. Timer(this.widget.backgroundLockLatency, () => this.showLockScreen());
  75. }
  76. if (state == AppLifecycleState.resumed) {
  77. this._backgroundLockLatencyTimer?.cancel();
  78. }
  79. super.didChangeAppLifecycleState(state);
  80. }
  81. @override
  82. void dispose() {
  83. WidgetsBinding.instance.removeObserver(this);
  84. this._backgroundLockLatencyTimer?.cancel();
  85. super.dispose();
  86. }
  87. @override
  88. Widget build(BuildContext context) {
  89. return MaterialApp(
  90. home: this.widget.enabled ? this._lockScreen : this.widget.builder(null),
  91. navigatorKey: _navigatorKey,
  92. themeMode: widget.savedThemeMode,
  93. theme: widget.lightTheme,
  94. darkTheme: widget.darkTheme,
  95. locale: widget.locale,
  96. debugShowCheckedModeBanner: false,
  97. supportedLocales: appSupportedLocales,
  98. localeListResolutionCallback: localResolutionCallBack,
  99. localizationsDelegates: const [
  100. ...AppLocalizations.localizationsDelegates,
  101. S.delegate,
  102. ],
  103. onGenerateRoute: (settings) {
  104. switch (settings.name) {
  105. case '/lock-screen':
  106. return PageRouteBuilder(
  107. pageBuilder: (_, __, ___) => this._lockScreen,
  108. );
  109. case '/unlocked':
  110. return PageRouteBuilder(
  111. pageBuilder: (_, __, ___) =>
  112. this.widget.builder(settings.arguments),
  113. );
  114. }
  115. return PageRouteBuilder(pageBuilder: (_, __, ___) => this._lockScreen);
  116. },
  117. );
  118. }
  119. Widget get _lockScreen {
  120. return WillPopScope(
  121. child: this.widget.lockScreen,
  122. onWillPop: () => Future.value(false),
  123. );
  124. }
  125. /// Causes `AppLock` to either pop the [lockScreen] if the app is already running
  126. /// or instantiates widget returned from the [builder] method if the app is cold
  127. /// launched.
  128. ///
  129. /// [args] is an optional argument which will get passed to the [builder] method
  130. /// when built. Use this when you want to inject objects created from the
  131. /// [lockScreen] in to the rest of your app so you can better guarantee that some
  132. /// objects, services or databases are already instantiated before using them.
  133. void didUnlock([Object? args]) {
  134. if (this._didUnlockForAppLaunch) {
  135. this._didUnlockOnAppPaused();
  136. } else {
  137. this._didUnlockOnAppLaunch(args);
  138. }
  139. }
  140. /// Makes sure that [AppLock] shows the [lockScreen] on subsequent app pauses if
  141. /// [enabled] is true of makes sure it isn't shown on subsequent app pauses if
  142. /// [enabled] is false.
  143. ///
  144. /// This is a convenience method for calling the [enable] or [disable] method based
  145. /// on [enabled].
  146. void setEnabled(bool enabled) {
  147. if (enabled) {
  148. this.enable();
  149. } else {
  150. this.disable();
  151. }
  152. }
  153. /// Makes sure that [AppLock] shows the [lockScreen] on subsequent app pauses.
  154. void enable() {
  155. setState(() {
  156. this._enabled = true;
  157. });
  158. }
  159. /// Makes sure that [AppLock] doesn't show the [lockScreen] on subsequent app pauses.
  160. void disable() {
  161. setState(() {
  162. this._enabled = false;
  163. });
  164. }
  165. /// Manually show the [lockScreen].
  166. Future<void> showLockScreen() {
  167. this._isLocked = true;
  168. return _navigatorKey.currentState!.pushNamed('/lock-screen');
  169. }
  170. void _didUnlockOnAppLaunch(Object? args) {
  171. this._didUnlockForAppLaunch = true;
  172. _navigatorKey.currentState!
  173. .pushReplacementNamed('/unlocked', arguments: args);
  174. }
  175. void _didUnlockOnAppPaused() {
  176. this._isLocked = false;
  177. _navigatorKey.currentState!.pop();
  178. }
  179. }