TypeAdapter
- Flutter course
- Advanced
- Lesson 13/69
- 4 min
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);
}Practice 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.
Starter code
import 'package:hive/hive.dart';
// User sınıfını tanımla
// final String name alanı olsun
// UserAdapter sınıfını yaz
// typeId = 0
// read ve write metodları
void main() async {
// adapter kaydet
// Hive'ı başlat
// 'users' box'ını aç
// 'u1' anahtarına User('Ayşe') koy
// değeri al ve ismini yazdır
}Sample 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();
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to register a custom class with Hive?
- JsonAdapter
- SqfliteAdapter
- TypeAdapter Correct answer
- StreamAdapter
Explanation: TypeAdapter teaches Hive how to store custom classes; it is registered with registerAdapter.
2 Register an adapter
Hive.____(UserAdapter());
Hive.registerAdapter(UserAdapter());
Explanation: To register an adapter with Hive you call registerAdapter; the adapter instance is passed as a parameter.
3 TypeAdapter parts
| Term | Meaning |
|---|---|
TypeAdapter |
Introduces custom class to Hive |
typeId |
Unique identifier |
@HiveType |
Marks the class |
registerAdapter |
Registers the adapter |