1
1
import 'package:flutter/material.dart' ;
2
2
import 'package:sample_app/app_themes.dart' ;
3
+ import 'package:shared_preferences/shared_preferences.dart' ;
3
4
4
5
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]];
14
18
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
+ }
18
30
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
+ }
23
42
}
0 commit comments