Why I Chose Hive Over Other Options

There are several local storage options in Flutter:

●    SharedPreferences: Good for tiny, simple data



●    SQLite: Powerful but needs boilerplate and third-party plugins



●    ObjectBox: Amazing but slightly heavier



●    Hive: Lightweight, fast, and requires no native dependencies



I went with Hive because:

●    It’s blazing fast

●    It supports complex data types with adapters



●    It supports encryption with AES



●    It works offline, cross-platform, and even on the web





Step 1: Installing Hive

To get started, I added the following dependencies in my pubspec.yaml:

  dependencies:
  hive: ^2.2.3
  hive_flutter: ^1.1.0
  path_provider: ^2.1.1
 
 dev_dependencies:
  hive_generator: ^2.0.1
  build_runner: ^2.4.6

 


●    hive: The core package



●    hiveflutter: Flutter-specific utilities (like Hive.initFlutter())

●    pathprovider: Used for storage paths on device



●    hivegenerator & buildrunner: Used to auto-generate type adapters for my custom models





Step 2: Initializing Hive

In my main.dart, I initialized Hive like this:

  void main() async {
  WidgetsFlutterBinding.ensureInitialized();
 
  // Initialize Hive for Flutter
  await Hive.initFlutter();
 
  // Register adapters (I’ll show how to create these)
  Hive.registerAdapter(UserAdapter());
 
  // Open a box
  await Hive.openBox(’settings’);
  await Hive.openBox<User>(’users’);
 
  runApp(MyApp());
 }   


You’ll notice I registered a UserAdapter. That’s needed for storing custom objects.



Step 3: Creating a Model and Adapter

Let’s say I want to store this User model locally:

  import ’package:hive/hive.dart’;
 
 part ’user.g.dart’;
 
 @HiveType(typeId: 0)
 class User extends HiveObject {
  @HiveField(0)
  String name;
 
  @HiveField(1)
  int age;
 
  User({required this.name, required this.age});
 }

 


Then, I generated the adapter by running:

 

  flutter pub run build_runner build

 


This created the user.g.dart file automatically. Now I could save and retrieve User objects securely.



Step 4: Performing CRUD Operations

Add or Update Data

 

 var box = Hive.box<User>(’users’);
 box.put(’current_user’, User(name: ’Muneeb’, age: 28));

 


Retrieve Data

 var currentUser = box.get(’current_user’);
 print(currentUser?.name); // Muneeb

 


Delete Data

 box.delete(’current_user’);

 


Listen to Changes

I even set up listeners for real-time updates:

 ValueListenableBuilder(
  valueListenable: Hive.box<User>(’users’).listenable(),
  builder: (context, box, _) {
    final user = box.get(’current_user’);
    return Text(user?.name ?? ’No user’);
  },
 )   



Step 5: Using Secure Encrypted Storage

This is my favorite part — Hive supports AES encryption out of the box. That means I can store user tokens, credentials, or sensitive data securely.

Generate a Secure Key

In production, I store this key securely using fluttersecurestorage, but for testing, I generated it like this:

 import ’package:hive/hive.dart’;
 import ’dart:convert’;
 import ’dart:math’;
 
 List<int> generateEncryptionKey() {
  final rand = Random.secure();
  return List<int>.generate(32, (_) => rand.nextInt(256));
 }
 
 final key = HiveAesCipher(generateEncryptionKey());

 


Open an Encrypted Box

 

  var secureBox = await Hive.openBox(
  ’secure_box’,
  encryptionCipher: HiveAesCipher(my32LengthSecureKey),

);

Save and Read Encrypted Data

 secureBox.put(’token’, ’123456abcd’);
 print(secureBox.get(’token’)); // Decrypted automatically

 


With this setup, even if someone accesses the raw .hive file, they won’t be able to read the data without the encryption key.



Step 6: Best Practices I Follow

  1. Register all adapters at app startup
  2.  Missing adapter registration leads to runtime crashes.


Use HiveObject and .save() for easy updates

 Example:

 
 user.name = ’Ali’;
 user.save();
     
  1. Avoid storing large blobs (like images)
  2.  Hive is best for structured data.


  3. Back up encryption key securely
  4.  Use fluttersecurestorage to store keys on Android/iOS keychain.




Step 7: Cleanup and Close Boxes

When closing the app or logging out, I clean up:

 await Hive.box(’secure_box’).close();
 await Hive.box<User>(’users’).clear(); // optional

 


You don’t have to close Hive boxes, but doing so can prevent memory leaks if your app has long-lived sessions or background services.



Things I Love About Hive

●    It’s blazing fast (no SQL parsing)



●    Offline-friendly and file-based



●    Easy to use, minimal setup



●    Cross-platform (Web, Desktop, Mobile)



●    Secure encryption support



●    Works great with Flutter’s reactive widgets (ValueListenableBuilder)





What I’d Improve or Be Cautious Of

●    No built-in support for queries (e.g., no .where() like databases)



●    Manual adapter generation can be annoying for large projects



●    Encrypted box key management is entirely up to me





Final Thoughts

Hive made my life so much easier when it came to secure local data storage in Flutter. Whether it’s storing app settings, user profiles, auth tokens, or even offline caches — Hive just works.

If you want:

●    Fast read/write operations



●    Custom object storage



●    Secure encryption



●    Seamless Flutter integration



then Hive should be your go-to

 

Our Trusted
Partner.

Unlock Valuable Cloud and Technology Credits

Imagine reducing your operational costs by up to $100,000 annually without compromising on the technology you rely on. Through our partnerships with leading cloud and technology providers like AWS (Amazon Web Services), Google Cloud Platform (GCP), Microsoft Azure, and Nvidia Inception, we can help you secure up to $25,000 in credits over two years (subject to approval).

These credits can cover essential server fees and offer additional perks, such as:

  • Google Workspace accounts
  • Microsoft accounts
  • Stripe processing fee waivers up to $25,000
  • And many other valuable benefits

Why Choose Our Partnership?

By leveraging these credits, you can significantly optimize your operational expenses. Whether you're a startup or a growing business, the savings from these partnerships ranging from $5,000 to $100,000 annually can make a huge difference in scaling your business efficiently.

The approval process requires company registration and meeting specific requirements, but we provide full support to guide you through every step. Start saving on your cloud infrastructure today and unlock the full potential of your business.

exclusive-partnersexclusive-partners

Let's TALK

Let's TALK and bring your ideas to life! Our experienced team is dedicated to helping your business grow and thrive. Reach out today for personalized support or request your free quote to kickstart your journey to success.

DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING
DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING