I am trying to save api data with hive, and got this error:
HiveError: Cannot write, unknown type: User. Did you forget to register an adapter?
How can I save my data from api with Hive adapters and display them?
My code:
static Future<User> getUser() async {
var url = '${Constants.API_URL_DOMAIN}action=user_profile&token=${Constants.USER_TOKEN}';
print(Constants.USER_TOKEN);
final response = await http.get(Uri.parse(url));
final body = jsonDecode(response.body);
var box = Hive.box('myBox');
box.put('user', User.fromJson(body['data']));
return User.fromJson(body['data']);
}
2
Answers
To save the objects in the hive, you first need to create an adapter. For example, if your
User
class has two propertiesname
andage
, your adapter will look like this:Then run
flutter pub run build_runner build
.After that, in the
main()
function. Don’t forgot to register that adapter, and open the box if needed. Eg:There are two ways to work with Flutter Hive Database.
You are trying to save the
User
class Object which is not a Primitive type, so you will have to use theHive Type Adapters
.If you do not want to use the type adapters, then you can directly save the json data that you are getting from the API call, and the modified code will look similar to this.