app_lock.dart 6.0 KB

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