2023-01-08 22:27:33 -05:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
2023-01-10 21:04:18 -05:00
|
|
|
import 'themes/themes.dart';
|
2023-01-08 22:27:33 -05:00
|
|
|
|
|
|
|
class ThemeService {
|
|
|
|
ThemeService._();
|
|
|
|
static late SharedPreferences prefs;
|
|
|
|
static ThemeService? _instance;
|
|
|
|
|
|
|
|
static Future<ThemeService> get instance async {
|
|
|
|
if (_instance == null) {
|
|
|
|
prefs = await SharedPreferences.getInstance();
|
|
|
|
_instance = ThemeService._();
|
|
|
|
}
|
|
|
|
return _instance!;
|
|
|
|
}
|
|
|
|
|
|
|
|
final allThemes = <String, ThemeData>{
|
|
|
|
'dark': darkTheme,
|
|
|
|
'light': lightTheme,
|
|
|
|
};
|
|
|
|
|
|
|
|
String get previousThemeName {
|
2023-07-26 14:20:29 -04:00
|
|
|
var themeName = prefs.getString('previousThemeName');
|
2023-01-08 22:27:33 -05:00
|
|
|
if (themeName == null) {
|
|
|
|
final isPlatformDark =
|
2023-07-22 23:29:10 -04:00
|
|
|
WidgetsBinding.instance.platformDispatcher.platformBrightness ==
|
|
|
|
Brightness.dark;
|
2023-07-26 15:58:38 -04:00
|
|
|
themeName = isPlatformDark ? 'dark' : 'light';
|
2023-01-08 22:27:33 -05:00
|
|
|
}
|
|
|
|
return themeName;
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:58:38 -04:00
|
|
|
ThemeData get initial {
|
2023-07-26 14:20:29 -04:00
|
|
|
var themeName = prefs.getString('theme');
|
2023-01-08 22:27:33 -05:00
|
|
|
if (themeName == null) {
|
|
|
|
final isPlatformDark =
|
2023-07-22 23:29:10 -04:00
|
|
|
WidgetsBinding.instance.platformDispatcher.platformBrightness ==
|
|
|
|
Brightness.dark;
|
2023-01-08 22:27:33 -05:00
|
|
|
themeName = isPlatformDark ? 'dark' : 'light';
|
|
|
|
}
|
2023-07-26 15:58:38 -04:00
|
|
|
return allThemes[themeName] ?? allThemes['light']!;
|
2023-01-08 22:27:33 -05:00
|
|
|
}
|
|
|
|
|
2023-07-26 15:58:38 -04:00
|
|
|
Future<void> save(String newThemeName) async {
|
2023-07-26 14:20:29 -04:00
|
|
|
final currentThemeName = prefs.getString('theme');
|
2023-01-08 22:27:33 -05:00
|
|
|
if (currentThemeName != null) {
|
2023-07-26 15:58:38 -04:00
|
|
|
await prefs.setString('previousThemeName', currentThemeName);
|
2023-01-08 22:27:33 -05:00
|
|
|
}
|
2023-07-26 15:58:38 -04:00
|
|
|
await prefs.setString('theme', newThemeName);
|
2023-01-08 22:27:33 -05:00
|
|
|
}
|
|
|
|
|
2023-07-26 14:20:29 -04:00
|
|
|
ThemeData getByName(String name) => allThemes[name]!;
|
2023-01-08 22:27:33 -05:00
|
|
|
}
|