app_state.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'package:pb_authenticator_state/state.dart';
  2. import 'package:pb_authenticator_totp/totp.dart';
  3. import 'package:flutter/widgets.dart';
  4. import 'package:collection/collection.dart' show ListEquality;
  5. import 'package:shared_preferences/shared_preferences.dart';
  6. import 'package:flutter/material.dart';
  7. // TODO: Transition to new type
  8. typedef BaseItemType = LegacyAuthenticatorItem;
  9. /// Represents app state.
  10. class AppState extends ChangeNotifier {
  11. final RepositoryBase<BaseItemType> _repository;
  12. // Theme and screen capture settings
  13. ThemeMode _themeMode = ThemeMode.system;
  14. bool _screenCapturePrevented = false;
  15. ThemeMode get themeMode => _themeMode;
  16. bool get screenCapturePrevented => _screenCapturePrevented;
  17. AppState(this._repository) {
  18. _loadSettings();
  19. }
  20. /// List of TOTP items (internal implementation).
  21. List<BaseItemType>? _items;
  22. /// TOTP items as list.
  23. List<BaseItemType>? get items {
  24. if (_items == null) {
  25. loadItems();
  26. }
  27. return _items;
  28. }
  29. Future loadItems() async {
  30. _items = await _repository.loadItems();
  31. notifyListeners();
  32. }
  33. /// Adds a TOTP item to the list.
  34. Future addItem(TotpItem item) async {
  35. await _repository.addItem(item);
  36. await loadItems();
  37. }
  38. /// Replace list of TOTP items.
  39. Future replaceItems(List<BaseItemType> items) async {
  40. await _repository.replaceItems(items);
  41. await loadItems();
  42. }
  43. bool itemsChanged(List<BaseItemType>? newItems) {
  44. return !const ListEquality().equals(items, newItems);
  45. }
  46. Future<void> _loadSettings() async {
  47. final prefs = await SharedPreferences.getInstance();
  48. final themeIndex = prefs.getInt('themeMode') ?? 0;
  49. _themeMode = ThemeMode.values[themeIndex];
  50. _screenCapturePrevented = prefs.getBool('screenCapturePrevented') ?? false;
  51. // Platform channel will handle screen capture prevention
  52. notifyListeners();
  53. }
  54. Future<void> setThemeMode(ThemeMode mode) async {
  55. _themeMode = mode;
  56. final prefs = await SharedPreferences.getInstance();
  57. await prefs.setInt('themeMode', mode.index);
  58. notifyListeners();
  59. }
  60. Future<void> setScreenCapturePrevented(bool value) async {
  61. _screenCapturePrevented = value;
  62. final prefs = await SharedPreferences.getInstance();
  63. await prefs.setBool('screenCapturePrevented', value);
  64. // Platform channel will handle screen capture prevention
  65. notifyListeners();
  66. }
  67. }