app_lock.dart 5.8 KB

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