Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f634b2

Browse files
committed
Added SharedPreferences to save loaded theme
1 parent b2043cb commit 8f634b2

File tree

1 file changed

+35
-16
lines changed

1 file changed

+35
-16
lines changed

‎sample_app/lib/theme_manager.dart

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,42 @@
11
import 'package:flutter/material.dart';
22
import 'package:sample_app/app_themes.dart';
3+
import 'package:shared_preferences/shared_preferences.dart';
34

45
class ThemeManager with ChangeNotifier {
5-
ThemeData _themeData;
6-
7-
/// Use this method on UI to get selected theme.
8-
ThemeData get themeData {
9-
if (_themeData == null) {
10-
_themeData = appThemeData[AppTheme.White];
11-
}
12-
return _themeData;
13-
}
6+
ThemeData _themeData;
7+
final String _kthemePreference = "theme_preference";
8+
9+
ThemeManager(){
10+
_loadTheme();
11+
}
12+
// Load saved theme
13+
void _loadTheme(){
14+
debugPrint("Entered loadTheme");
15+
SharedPreferences.getInstance().then((prefs){
16+
int preferedTheme = prefs.getInt(_kthemePreference) ?? 0;
17+
_themeData = appThemeData[AppTheme.values[preferedTheme]];
1418

15-
/// Sets theme and notifies listeners about change.
16-
setTheme(AppTheme theme) async {
17-
_themeData = appThemeData[theme];
19+
// Notify listeners
20+
notifyListeners();
21+
});
22+
}
23+
// Use this method on UI to get selected theme.
24+
ThemeData get themeData {
25+
if (_themeData == null) {
26+
_themeData = appThemeData[AppTheme.White];
27+
}
28+
return _themeData;
29+
}
1830

19-
// Here we notify listeners that theme changed
20-
// so UI have to be rebuild
21-
notifyListeners();
22-
}
31+
// Sets theme and notifies listeners about change.
32+
setTheme(AppTheme theme) async {
33+
_themeData = appThemeData[theme];
34+
35+
// Save the selected theme into Sharedpreferences
36+
var prefs = await SharedPreferences.getInstance();
37+
prefs.setInt(_kthemePreference, AppTheme.values.indexOf(theme));
38+
// Here we notify listeners that theme changed
39+
// so UI have to be rebuild
40+
notifyListeners();
41+
}
2342
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /