skip to Main Content

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


  1. To save the objects in the hive, you first need to create an adapter. For example, if your User class has two properties name and age, your adapter will look like this:

    part 'user.g.dart';
    @HiveType(typeId: 0)
    class User{
      @HiveField(0)
      final String title;
      @HiveField(1)
      final int age;
    
      User({this.title, this.age});
    
      // other methods: fromJson, toJson
    }
    

    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:

    void main() async {
      await Hive.initFlutter();
      Hive
        ..registerAdapter(UserAdapter());
      await Hive.openBox<User>('usersbox');
    }
    
    Login or Signup to reply.
  2. There are two ways to work with Flutter Hive Database.

    1. Saving the Primitive data (such as List, Map, DateTime, BigInt, etc) directly into the Hive Box
    2. Non-Primitve data using the Hive Type Adapters. (for more info check this)

    You are trying to save the User class Object which is not a Primitive type, so you will have to use the Hive 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.

     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', body['data']);
        return User.fromJson(body['data']);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search