Line data Source code
1 : import "dart:async"; 2 : 3 : import "package:errorlookup/core/data/source/settings_data_source.dart"; 4 : import "package:errorlookup/core/models/result.dart"; 5 : import "package:errorlookup/core/models/theme_data.dart"; 6 : import "package:shared_preferences/shared_preferences.dart"; 7 : 8 : /// データ層の実装 9 : class LocalSettingsDataSource implements SettingsDataSource { 10 : /// テーマ設定のプリファレンスマップ 11 : static const _themeValue = { 12 : ThemeMode.system: "theme_system", 13 : ThemeMode.dark: "theme_dark", 14 : ThemeMode.light: "theme_light" 15 : }; 16 : 17 : /// テーマ設定のインバースマップ 18 2 : static final _themeValueInverse = 19 3 : _themeValue.map((key, value) => MapEntry(value, key)); 20 : 21 : static const _themeKey = "theme"; 22 : 23 : /// テーマ設定のストリーム 24 : final _themeSettingStreamController = StreamController<ThemeMode>.broadcast(); 25 : 26 1 : LocalSettingsDataSource({bool initialize = true}) { 27 : if (initialize) { 28 1 : init(); 29 : } 30 : } 31 : 32 1 : Future<void> init() async { 33 1 : final prefs = await SharedPreferences.getInstance(); 34 1 : final savedValue = prefs.getString(_themeKey); 35 : if (savedValue == null) { 36 1 : prefs.setString(_themeKey, "theme_system"); 37 2 : _themeSettingStreamController.sink 38 3 : .add(_themeValueInverse["theme_system"]!); 39 : } else { 40 5 : _themeSettingStreamController.sink.add(_themeValueInverse[savedValue]!); 41 : } 42 : } 43 : 44 1 : @override 45 : Stream<ThemeMode> getThemeSettingStream() { 46 2 : return _themeSettingStreamController.stream; 47 : } 48 : 49 1 : @override 50 : Future<Result<bool, Exception>> saveThemeSetting( 51 : {required final ThemeMode newMode}) async { 52 1 : final prefs = await SharedPreferences.getInstance(); 53 1 : final convertedValue = _themeValue[newMode]; 54 : if (convertedValue == null) { 55 0 : return Failure(Exception("preference value is not found")); 56 : } 57 1 : final ret = await prefs.setString(_themeKey, convertedValue); 58 : if (!ret) { 59 0 : return Failure(Exception("SharedPreferences.setString fail")); 60 : } 61 3 : _themeSettingStreamController.sink.add(newMode); 62 : return const Success(true); 63 : } 64 : }