Question
What's the correct way to use Hive for app theming (light/dark mode)?
Code sample
class Application extends StatelessWidget {
Future _openBoxes() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
return Future.wait([
Hive.openBox('settings'),
Hive.openBox('favorites'),
]);
}
Future _getTheme(BuildContext context) async {
var settingsBox = Hive.box('settings');
var theme = settingsBox.get('theme') ?? 'light';
print("Theme from box: $theme");
var materialTheme;
switch (theme) {
case 'light': {
materialTheme = ThemesStyles.light(context);
break;
}
case 'dark': {
materialTheme = ThemesStyles.dark(context);
break;
}
case 'black': {
materialTheme = ThemesStyles.black(context);
break;
}
default: materialTheme = ThemesStyles.light(context);
}
return materialTheme;
}
@override
Widget build(BuildContext context) {
final ThemeProvider themeProvider = Provider.of<ThemeProvider>(context);
return FutureBuilder(
future: _openBoxes(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return FutureBuilder(
future: _getTheme(context),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: snapshot.hasData ? snapshot.data : ThemesStyles.black(context),
routes: routes(context),
home: ScrollConfiguration(
behavior: BounceScrollBehavior(),
child: HomePage(),
)
);
}
);
}
);
}
}
Link to file: https://github.com/holt-soundboard/holt-soundboard-mobile/blob/master/lib/main.dart
As seen, I have nested FutureBuilders(), one for opening boxes, one for getting the theme, which I thought would work. However, this doesn't work in production (release app).
Version
Your _getTheme() method does not need to be async. This already removes one FutureBuilder.
What error are you seeing?
@leisim
Thank you for your quick reply, I will try this!
And I'm sorry to cause you inconvenience, but the error was actually on my side (Gradle errors) after downloading the app from the PlayStore. Hive has worked amazing!
Glad you like it. Don't hesitate to ask if you need further assistance.