Flutter
TypeAdapter
Register a custom class with TypeAdapter.
What is a TypeAdapter?
A TypeAdapter is a converter that teaches Hive how to store and read custom classes. Each adapter has a unique typeId and is registered with Hive.registerAdapter. Without a registered adapter, you cannot put a custom type into a box.
class UserAdapter extends TypeAdapter<User> {
@override
final int typeId = 0;
// read and write methods
}
@HiveType and @HiveField
You mark model classes with @HiveType(typeId: 0) and order each field with @HiveField(0), @HiveField(1) and so on. These annotations generate adapters via code generation. Writing adapters by hand is also possible, but annotations are more convenient.
@HiveType(typeId: 0)
class User extends HiveObject {
@HiveField(0)
final String name;
User(this.name);
}
Exercise Write and use a UserAdapter
Define a User class (final String name). Write a UserAdapter with typeId 0 and read/write methods. Register the adapter, initialize Hive, open a box named 'users', put User('Ayşe') under key 'u1', retrieve it and print the name.
Show example solution
import 'package:hive/hive.dart';
class User {
final String name;
User(this.name);
}
class UserAdapter extends TypeAdapter<User> {
@override
final int typeId = 0;
@override
User read(BinaryReader reader) {
return User(reader.readString());
}
@override
void write(BinaryWriter writer, User obj) {
writer.writeString(obj.name);
}
}
void main() async {
Hive.registerAdapter(UserAdapter());
Hive.init('hive_data');
final box = await Hive.openBox('users');
await box.put('u1', User('Ayşe'));
final user = box.get('u1') as User;
print(user.name);
await box.close();
}
Test yourself
-
What is used to register a custom class with Hive?
- JsonAdapter
- SqfliteAdapter
- TypeAdapter
- StreamAdapter
Show answer
TypeAdapter — TypeAdapter teaches Hive how to store custom classes; it is registered with registerAdapter.
-
Register an adapter
Hive.____(UserAdapter());
Show answer
Hive.registerAdapter(UserAdapter());
-
TypeAdapter parts
- TypeAdapter
- Introduces custom class to Hive
- typeId
- Unique identifier
- @HiveType
- Marks the class
- registerAdapter
- Registers the adapter
Next lesson: HiveList and lazy box