I have a Flutter app that retrieves a JSON document from a website and then saves it using Hive. I have a LocalDatabase class that extends HiveObject and contains several objects and lists of custom objects.
Here is the code for the LocalDatabase class:
part 'hive_storage.g.dart';
@HiveType(typeId: 0)
class LocalDatabase extends HiveObject {
@HiveField(0)
DateTime? lastUpdate;
List<Schulaufgaben>? examDates;
List<AllgemeineTermine>? appointments;
Schulinformationen? schoolInformation;
}
The Schulaufgaben and AllgemeineTermine classes are custom objects that have their own fromJson() and toJson() methods for serialization and deserialization. The LocalDatabase class also has corresponding Hive adapters generated using Hive's code generation (hive_generator).
I am able to save and retrieve data using Hive while the app is running. However, after restarting the app, all the objects and lists of custom objects in the LocalDatabase object except for lastUpdate are null.
I have properly initialized Hive in my main function as follows:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
Hive.registerAdapter(LocalDatabaseAdapter());
await Hive.openBox<LocalDatabase>('localDatabase');
runApp(const MyApp());
}
And here is how I save the LocalDatabase object to Hive after retrieving data from the website:
final localDatabase = Boxes.getSavedDatabase();
final databaseObject = LocalDatabase()
..lastUpdate = DateTime.now()
..examDates = await _db.getExamDates()
..appointments = await _db.getAppointments();
localDatabase.add(databaseObject);
I am not sure why the custom objects and lists of custom objects are not persisted in Hive after restarting the app.
I have also checked that the custom objects and lists of custom objects are properly registered with Hive using Hive.registerAdapter().
I have referred to a similar issue on Stack Overflow (link: Flutter Hive save custom object with list of custom objects gone after restarting app) but the solutions provided there did not work for me. I have also tried using the hive_flutter package for Flutter-specific implementations, but the issue persists.