'Insert dark theme in settings_ui dependencies
I implemented settings_ui in dependencies on Flutter.
I'm trying to use a tile to set the theme but I get the error:
NoSuchMethodError (NoSuchMethodError: The method 'getBool' was called on null.
Receiver: null
Tried calling: getBool("theme"))
I don't know why I get this error since I initialized the bool value... Tell me if you need something else in comments.
settings.dart
void main() => runApp(Settings());
class Settings extends KFDrawerContent {
@override
_ImpostazioniAppState createState() => _ImpostazioniAppState();
}
class _SettingsState extends State<SettingsApp> {
SharedPreferences _prefs;
final String _keyTheme = "theme";
bool darktheme = false;
@override
Widget build(BuildContext context) {
bool temaDark = _prefs.getBool(_keyTheme) ?? true;
return SettingsList(
sections: [
SettingsSection(
title: Text('Common'),
tiles: <SettingsTile>[
SettingsTile.navigation(
leading: Icon(Icons.language),
title: Text('Language'),
value: Text('English'),
),
SettingsTile.switchTile(
onToggle: (value) {
_prefs.setBool(_keyTheme, value);
},
initialValue: darktheme,
leading: Icon(Icons.format_paint),
title: Text('Enable custom theme'),
),
],
),
],
);
}
}
theme_provider.dart
class ThemeNotifier extends ChangeNotifier {
final String key = "theme";
SharedPreferences _prefs;
bool _darkTheme;
bool get darkTheme => _darkTheme;
ThemeNotifier() {
_darkTheme = true;
_loadFromPrefs();
}
toggleTheme() {
_darkTheme = !_darkTheme;
_saveToPrefs();
notifyListeners();
}
_initPrefs() async {
if (_prefs == null) _prefs = await SharedPreferences.getInstance();
}
_loadFromPrefs() async {
await _initPrefs();
_darkTheme = _prefs.getBool(key) ?? true;
notifyListeners();
}
_saveToPrefs() async {
await _initPrefs();
_prefs.setBool(key, _darkTheme);
}
}
For the dark theme, I followed this guide and maybe there is something wrong.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|