53 lines
1.3 KiB
Dart
53 lines
1.3 KiB
Dart
/// [ChangeNotifier] that owns [ThemeMode] and persists it locally.
|
|
library;
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import '../services/storage_service.dart';
|
|
|
|
/// Provides [themeMode] to [MaterialApp] and writes changes to storage.
|
|
class ThemeController extends ChangeNotifier {
|
|
ThemeController(this._storage) {
|
|
_themeMode = _fromName(_storage.themeModeName);
|
|
}
|
|
|
|
final StorageService _storage;
|
|
late ThemeMode _themeMode;
|
|
|
|
ThemeMode get themeMode => _themeMode;
|
|
|
|
bool get isDark =>
|
|
_themeMode == ThemeMode.dark ||
|
|
(_themeMode == ThemeMode.system &&
|
|
WidgetsBinding.instance.platformDispatcher.platformBrightness ==
|
|
Brightness.dark);
|
|
|
|
Future<void> setThemeMode(ThemeMode mode) async {
|
|
if (mode == _themeMode) return;
|
|
_themeMode = mode;
|
|
notifyListeners();
|
|
await _storage.setThemeModeName(_toName(mode));
|
|
}
|
|
|
|
/// Toggles between light and dark (moon / sun control).
|
|
Future<void> toggleLightDark() {
|
|
return setThemeMode(isDark ? ThemeMode.light : ThemeMode.dark);
|
|
}
|
|
}
|
|
|
|
ThemeMode _fromName(String name) {
|
|
return switch (name) {
|
|
'dark' => ThemeMode.dark,
|
|
'system' => ThemeMode.system,
|
|
_ => ThemeMode.light,
|
|
};
|
|
}
|
|
|
|
String _toName(ThemeMode mode) {
|
|
return switch (mode) {
|
|
ThemeMode.light => 'light',
|
|
ThemeMode.dark => 'dark',
|
|
ThemeMode.system => 'system',
|
|
};
|
|
}
|