In my Flutter project I have set up static local repository functions where I can perform CRUD operations easily. I would serialize my Flutter objects into Map<String, dynamic> instances (JSON-like) using toJson() function generated by Freezed package.
But as I try to retrieve the data, an error stacktrace shows:
E/flutter ( 6461): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_Map<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>?' in type cast
E/flutter ( 6461): #0 BoxImpl.get (package:hive/src/box/box_impl.dart:44:26)
E/flutter ( 6461): #1 LocalRepository.getAppWatchlist (package:project_intervene/services/repository/local/local_repository.dart:30:14)
...
It's really weird because I did explicitly state the type of my Hive Boxes to be in type <Map<String, dynamic>>, as proven by the following snippet.
await Hive.initFlutter();
await Hive.openBox<Map<String, dynamic>>(BOX_APP_WATCHLIST);
The GET function looks like this:
static Future<AppWatchlist?> getAppWatchlist() async {
Map<String, dynamic>? data =
Hive.box<Map<String, dynamic>>(BOX_APP_WATCHLIST)
.get(KEY_APP_WATCHLIST); // <-- Where #1 stacktrace is pointing
return data == null ? null : AppWatchlist.fromJson(data);
}
The AppWatchlist model class is partially generated by Freezed.
What I have tried...
I tried to use Map<String, dynamic>.from(), but it does not work as the error occurs internally with Hive's get method. I couldn't even get the data.
When I try to store the object as strings, it cannot be decoded back into JSON properly as the keys and values do not have the quotation marks around them (JSON cannot determine their types that way). I also don't really want to store them as strings because of performances, unless if it really is the last resort.
Weird phenomenon
A strange phenomenon is that retrieving data did actually work, but seemingly only after I used the Update operation (of the same Hive box and key) once! The updater method looks like this:
static void setAppWatchlist(AppWatchlist appWatchlist) {
Hive.box<Map<String, dynamic>>(BOX_APP_WATCHLIST)
.put(KEY_APP_WATCHLIST, appWatchlist.toJson());
}