Setting up Hive Database in Flutter Application
Hive is a NoSQL key-value storage for Flutter, written in pure Dart without native dependencies. Runs on all platforms: iOS, Android, Web, and Desktop. The main advantage is speed: read operations are significantly faster than SQLite for simple objects, because Hive stores data in binary format and keeps frequently used boxes in memory.
What We're Configuring
Add to pubspec.yaml:
dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
dev_dependencies:
hive_generator: ^2.0.1
build_runner: ^2.4.6
Initialize in main() before runApp:
await Hive.initFlutter();
Hive.registerAdapter(UserAdapter());
await Hive.openBox<User>('users');
runApp(const MyApp());
TypeAdapters for custom objects. Hive cannot store arbitrary Dart classes without an adapter. Annotate your model:
@HiveType(typeId: 0)
class User extends HiveObject {
@HiveField(0)
late String id;
@HiveField(1)
late String name;
}
Run code generation: flutter pub run build_runner build. This generates user.g.dart with UserAdapter. The typeId must be unique throughout the application. Conflicting typeId values cause HiveError when opening the box.
Encrypted box. For sensitive data (tokens, user credentials), use an encrypted box. The encryption key is generated via Hive.generateSecureKey() and stored in flutter_secure_storage, not in SharedPreferences or Hive itself:
final secureStorage = const FlutterSecureStorage();
var encryptionKey = await secureStorage.read(key: 'hive_key');
if (encryptionKey == null) {
final key = Hive.generateSecureKey();
await secureStorage.write(key: 'hive_key', value: base64Url.encode(key));
encryptionKey = base64Url.encode(key);
}
final encryptedBox = await Hive.openBox('secureBox',
encryptionCipher: HiveAesCipher(base64Url.decode(encryptionKey)));
Common Mistakes
Opening a box multiple times: Hive.openBox for an already-open box returns the existing instance, but calling Hive.box('name') before opening throws HiveError: Box not found. Recommendation: open all required boxes in main() and access them via Hive.box<T>('name') throughout your code.
Forgetting to close boxes on shutdown: call Hive.close() in dispose() or via WidgetsBindingObserver. In production on iOS, this can cause data loss if the app is force-closed.
Timeline
Hive setup with basic CRUD operations and 2–3 models: 4–8 hours. With encryption and code generation across the project: 1–2 days. Cost calculated individually.







