init method
ThemeServiceHive's init implementation. Must call be before accessing the storage box.
- Registers Hive data type adapters for our enum values
- Gets a usable platform appropriate folder where data can be stored.
- Open the box in the folder with name given via class constructor.
- Assign box to local Hive box instance.
Implementation
@override
Future<void> init() async {
// First register all Hive data type adapters. Used for our enum values.
registerHiveAdapters();
// Get platform compatible storage folder for the Hive box,
// this setup should work on all Flutter platforms. Hive does not do this
// right, the folder we got with it did not work on Windows. This
// implementation works and it uses the same folder that SharedPreferences
// does.
final String appDataDir = await _getAppDataDir();
// To make it easier to find the files on your device, this should help.
// Usually you find the "shared_preferences.json" file in the same folder
// that the ThemeServicePref creates with SharedPreferences. You cannot
// set the name on that file so all examples would have shared the same
// settings on local builds if SharedPreferences would have been used for
// all examples. Wanted to avoid that, which we can do with Hive. Sure we
// could have used only Hive too, but SharedPreferences is a very popular
// choice for this type of feature. I wanted to show how it can be
// used as well. We always show this path info in none release builds.
if (_debug) {
debugPrint('Hive using storage path: $appDataDir and file name: $boxName');
}
// Init the Hive box box giving it the platform usable folder.
Hive.init(appDataDir);
// Open the Hive box with passed in name, we just keep it open all the
// time in this demo app.
await Hive.openBox<dynamic>(boxName);
// Assign the box to our instance.
_hiveBox = Hive.box<dynamic>(boxName);
}