On this page15 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. The Model Class
- 2. Generate the Adapter
- 3. Rules That Protect Saved Data
- 4. Register the Adapter
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Key Takeaways
- Full Code (Copy-Paste Reference)
Lecture 003: The Model Class & Type Adapter
| Category | 2: Models & Manager |
| Lecture | 003 of 007 |
| Estimated video length | 22 min |
| Target | Flutter 3.44 · Dart 3.12 · hive 2.2 |
| Level | Beginner |
| Video | Part 1: Introduction, Setup, Model Adapters & Manager Classes |
| Source code | GitHub: urraan_hive_final_code |
A box can hold text and numbers, but our contacts have a name, an address, a photo and hobbies. We describe that as a Dart class, then let Hive's generator write the code that turns it into bytes: the type adapter.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lectures 001–002 and Dart classes with fields and List<String>.
Connection With Previous Lectures
Lecture 002 stored a String. Hive knows how to save String, int, bool, List, Map
and Uint8List. It does not know your DataObjects class: so we must teach it.
Learning Objectives
- Annotate a class with
@HiveTypeand fields with@HiveField - Run
build_runnerto generate the adapter - Choose
typeIdand field numbers, and know why they must never change - Give fields
defaultValues so old records still load
1. The Model Class
// lib/data_hive/data_objects.dart
import 'dart:typed_data';
import 'package:hive/hive.dart';
part 'data_objects.g.dart';
@HiveType(typeId: 0)
class DataObjects {
@HiveField(0)
dynamic key;
@HiveField(1, defaultValue: '')
String name = '';
@HiveField(2, defaultValue: '')
String address = '';
@HiveField(3)
Uint8List? profileImage;
@HiveField(4, defaultValue: [])
List<String> hobbies = [];
}Line by line:
part 'data_objects.g.dart';: the generated file becomes part of this one.@HiveType(typeId: 0): a unique id for this class across the whole app (0–223).@HiveField(n): the field's permanent number. Hive saves numbers, not names.key: we store the record's own key inside the object so a screen can update or delete it later. It isdynamicbecause Hive keys may beintorString.defaultValue: used when an old record does not have that field yet.Uint8List?: the photo's bytes;nullmeans "no photo".
2. Generate the Adapter
dart run build_runner build --delete-conflicting-outputsThis creates data_objects.g.dart containing DataObjectsAdapter. Run it again every time
you add or change a field. While developing you can use watch instead of build.
3. Rules That Protect Saved Data
| Rule | Why |
|---|---|
Never reuse or renumber a @HiveField | Old records would load into the wrong fields |
Never change typeId | Hive could not find the adapter |
Add new fields with new numbers and a defaultValue | Old records still open |
Do not edit .g.dart | It is overwritten on the next build |
4. Register the Adapter
An adapter must be registered once before its box is opened:
Hive.registerAdapter(DataObjectsAdapter());We do that inside the manager in Lecture 004, guarded by isAdapterRegistered.
Code Examples
Example 1: Add a New Field Later
Suppose we want an age. Next free number is 5:
@HiveField(5, defaultValue: 0)
int age = 0;Run build_runner again. Records saved before the change load with age == 0: nothing is
lost.
Common Beginner Mistakes
1. Forgetting part '...g.dart': the generator has nowhere to write; the analyzer
complains that DataObjectsAdapter does not exist.
2. Not running build_runner: the .g.dart file is missing, so DataObjectsAdapter is
undefined.
3. Renumbering fields: swapping @HiveField(1) and (2) makes old names load as
addresses. Numbers are forever.
4. Registering the adapter twice: Hive throws. Guard with Hive.isAdapterRegistered.
Best Practices
- Give every non-nullable field a
defaultValue. - Keep a comment of the highest field number used.
- Store large blobs (images) sparingly: see Lecture 007.
Mini Challenge
Add @HiveField(5, defaultValue: 0) int age, regenerate, and open data_objects.g.dart to
find where age appears in both read and write.
Practice Questions
- What does
typeIdidentify? 2. Why numbers instead of names? 3. Which command creates the adapter? 4. What happens to old records when you add a field with a default?
Practice Answers
- The class, uniquely, inside the app.
- Numbers keep old data readable if a field is renamed.
dart run build_runner build --delete-conflicting-outputs.- They load normally and the new field gets its default.
Key Takeaways
@HiveType+@HiveFielddescribe the class;build_runnerwrites the adapter.- Field numbers and
typeIdnever change; new fields get new numbers. - Register the adapter before opening the box.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file. The manager
class that currently calls these pieces together arrives in Lecture 004: for now main.dart
does it directly.
lib/data_hive/data_objects.dart: the model
// The Hive model. @HiveType/@HiveField numbers are permanent once real data exists -
// see the rules table above before ever changing one.
import 'dart:typed_data';
import 'package:hive/hive.dart';
// Links this file to the generated adapter below.
part 'data_objects.g.dart';
@HiveType(typeId: 0) // unique id for this class across the whole app
class DataObjects {
@HiveField(0)
dynamic key; // the record's own box key, stored on itself for easy update/delete
@HiveField(1, defaultValue: '')
String name = '';
@HiveField(2, defaultValue: '')
String address = '';
@HiveField(3)
Uint8List? profileImage; // raw photo bytes; null = no photo
@HiveField(4, defaultValue: [])
List<String> hobbies = [];
}lib/data_hive/data_objects.g.dart: generated adapter (reference only)
// GENERATED CODE - DO NOT MODIFY BY HAND.
// Produced by: dart run build_runner build --delete-conflicting-outputs
// Shown here so you can see what hive_generator writes for you - never hand-edit
// this file; just regenerate it whenever data_objects.dart changes.
part of 'data_objects.dart';
class DataObjectsAdapter extends TypeAdapter<DataObjects> {
@override
final int typeId = 0;
@override
DataObjects read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return DataObjects()
..key = fields[0]
..name = fields[1] as String
..address = fields[2] as String
..profileImage = fields[3] as Uint8List?
..hobbies = (fields[4] as List).cast<String>();
}
@override
void write(BinaryWriter writer, DataObjects obj) {
writer
..writeByte(5) // number of fields being written
..writeByte(0)
..write(obj.key)
..writeByte(1)
..write(obj.name)
..writeByte(2)
..write(obj.address)
..writeByte(3)
..write(obj.profileImage)
..writeByte(4)
..write(obj.hobbies);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DataObjectsAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}lib/main.dart
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'data_hive/data_objects.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
// Must happen before openBox<DataObjects> - Hive needs the adapter to know how
// to turn a DataObjects instance into bytes and back.
Hive.registerAdapter(DataObjectsAdapter());
await Hive.openBox<DataObjects>('DataObjects');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(colorSchemeSeed: Colors.deepPurple),
// No screens use the typed box yet - that starts with the manager in Lecture 004.
home: const Scaffold(body: Center(child: Text('DataObjects box is ready'))),
);
}
}