Search code examples
flutterflutter-hive

How do I define a TypeAdapter?


I am currently using the Hive database to store data. I run the below code:

main() async {
  runApp(MyApp());
  await Hive.initFlutter();
  Hive.registerAdapter(exerciseAdapter());
  await Hive.openBox('exerciseBox');
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
} 

But it says exerciseAdapter() is not defined. How do I register this type adapter?


Solution

  • I cannot see your imports, but it seems you haven't defined the exerciseAdapter() method or imported it from another file. To register a type adapter in Hive, you need to create a custom adapter for your class (e.g., Exercise) and then register it using Hive.registerAdapter().

    First, you need to create the custom adapter for your Exercise class. Assuming you have a class called Exercise, follow these steps:

    Add hive_generator and build_runner dependencies to your pubspec.yaml file:

    dependencies:
      hive: ^2.2.3
      ...
    
    dev_dependencies:
      hive_generator: ^2.0.0
      build_runner: ^2.3.3
      ...
    

    Create a file for your Exercise class (e.g., exercise.dart) and import the required packages:

    import 'package:hive/hive.dart';
    
    part 'exercise.g.dart';
    

    Define your Exercise class and annotate it with @HiveType:

    @HiveType(typeId: 0)
    class Exercise extends HiveObject {
      @HiveField(0)
      String name;
    
      @HiveField(1)
      int duration;
    
      Exercise({required this.name, required this.duration});
    }
    
    

    Run the build command to generate the adapter file exercise.g.dart:

    flutter pub run build_runner build
    

    Finally, import the generated adapter file and register it in your main() function:

    
    import 'package:hive/hive.dart';
    import 'package:hive_flutter/hive_flutter.dart';
    import 'package:flutter/services.dart';
    import 'exercise.dart';
    
    void main() async {
      await Hive.initFlutter();
      Hive.registerAdapter(ExerciseAdapter());
      await Hive.openBox<Exercise>('exerciseBox');
    
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    
      runApp(MyApp());
    }