how-to-handle-offline-data-storage-in-flutter-using-hive

How to Handle Offline Data Storage in Flutter Using Hive?

Offline data storage is a core feature in most modern apps, especially those built with Flutter. Whether saving user inputs, caching API responses, or building tools without internet access, managing local data efficiently is essential. Hive offers a lightweight, fast, and Dart-native solution for offline storage. It supports secure data handling and works well across mobile, web, and desktop platforms. This guide explains how to handle offline data storage in Flutter using Hive. Ready to level up your Flutter app’s performance even without a connection? Let’s dive in.

Why Local Data Storage Matters in Flutter

Data storage locally is a requirement for almost every app. Whether you want to cache REST API responses, build an application that runs offline, or store customer information for a food delivery app, offline storage is essential.

Flutter offers several local persistence solutions:

shared_preferences: Best for small key-value pairs.

sqflite: Ideal for complex relationships in relational data.

Hive: A fast, secure, lightweight, and Dart-native key-value database—perfect for Flutter Web and offline-first apps.

We’ll explore using Hive in Flutter to perform full offline CRUD operations and build a sample user list app.

Why Hive?

Hive is:

  • Written in pure Dart
  • Blazing fast (benchmarked faster than sqflite)
  • AES-256 encrypted for security
  • Compatible with Flutter Web

How Do You Get Started with Hive in Flutter?

Step 1: Add Dependencies

Add the following to your pubspec.yaml:

				
					dependencies:
  flutter:
    sdk: flutter
  hive: ^2.2.3
  hive_flutter: ^1.1.0
dev_dependencies:
  flutter_test:
    sdk: flutter
  hive_generator: ^1.1.3
  build_runner: ^2.2.0

				
			

This setup includes the core Hive package and the Flutter extension for UI integration. build_runner and hive_generator are required to generate adapters.

Step 2: Initialize Hive

Initialize Hive in your main.dart before calling runApp():

				
					void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(UserModelAdapter());
  await Hive.openBox('userBox');
  runApp(const MyApp());
}

				
			

This ensures Hive is ready and the userBox is open for use. Registering the adapter is mandatory for custom object storage.

Step 3: Define the Model and Generate Adapter

Create a new file named user_model.dart and define the model:

				
					import 'package:hive/hive.dart';
part 'user_model.g.dart';
@HiveType(typeId: 0)
class UserModel extends HiveObject {
  @HiveField(0)
  final String name; 
  @HiveField(1)
  final String hobby; 
  @HiveField(2)
  final String description;
  UserModel({
    required this.name,
    required this.hobby,
    required this.description,
  });
}

				
			

Now, run this command to generate the adapter:

				
					flutter packages pub run build_runner build
				
			

This command creates user_model.g.dart, allowing Hive to serialize and deserialize the model data.

Performing CRUD Operations with Hive

Once Hive is set up, you can perform CRUD (Create, Read, Update, Delete) operations on your data.

1. Add Data

To add a user to the Hive box:

				
					var userBox = Hive.box('users');
userBox.add(User(name: 'Alice', age: 30));
				
			

Use the add() method to insert a new entry into the box. Hive will automatically assign the entry a key.

2. Read Data

To retrieve data from the box:

				
					var userBox = Hive.box('users');
User? user = userBox.getAt(0);
				
			

Using getAt (), you can retrieve a user by their index. This makes reading values quick and straightforward.

3. Update Data

To update a user’s data:

				
					userBox.putAt(0, User(name: 'Alice', age: 31)); 
				
			

Updating a record requires its index. Use putAt() to replace the object at that specific index.

4. Delete Data

To delete a user from the box:

				
					userBox.deleteAt(0);
				
			

Use deleteAt() to remove an entry at the given index. The change will be reflected instantly in the UI with ValueListenableBuilder.

Building the UI

Here’s the full UI and logic for the Flutter Hive CRUD App.

File: main.dart

				
					import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'user_model.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(UserModelAdapter());
  await Hive.openBox('userBox');
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key}); 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Hive Database',
      home: UserListScreen(),
    );
  }
}
class UserListScreen extends StatelessWidget {
  final Box box = Hive.box('userBox');
  void showUserDialog(BuildContext context, {UserModel? user, int? index}) {
    final nameController = TextEditingController(text: user?.name);
    final hobbyController = TextEditingController(text: user?.hobby);
    final descController = TextEditingController(text: user?.description);
   showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text(user == null ? 'Add User' : 'Update User'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(controller: nameController, decoration: InputDecoration(labelText: 'Name')),
            TextField(controller: hobbyController, decoration: InputDecoration(labelText: 'Hobby')),
            TextField(controller: descController, decoration: InputDecoration(labelText: 'Description')),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              final userModel = UserModel(
                name: nameController.text,
                hobby: hobbyController.text,
                description: descController.text,
              );
              if (user == null) {
                box.add(userModel);
              } else if (index != null) {
                box.putAt(index, userModel);
              }
              Navigator.pop(context);
            },
            child: Text(user == null ? 'Add' : 'Update'),
          ),
        ],
      ),
    );
  }
  void confirmDelete(BuildContext context, int index) {
    final user = box.getAt(index);
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text('Are you sure you want to delete ${user?.name}?'),
        actions: [
          TextButton(
            onPressed: () {
              box.deleteAt(index);
              Navigator.pop(context);
            },
            child: const Text('Yes'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('No'),
          ),
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Hive Database')),
      body: ValueListenableBuilder(
        valueListenable: box.listenable(),
        builder: (context, Box box, _) {
          return ListView.builder(
            itemCount: box.length,
            itemBuilder: (context, index) {
              final user = box.getAt(index);
              return Card(
                margin: const EdgeInsets.all(8.0),
                child: ListTile(
                  title: Text('${user?.name} | ${user?.description}'),
                  subtitle: Text('Hobby: ${user?.hobby}'),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.edit),
                        onPressed: () => showUserDialog(context, user: user, index: index),
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => confirmDelete(context, index),
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => showUserDialog(context),
        child: const Icon(Icons.add),
      ),
    );
  }
}

				
			

This UI allows users to add, view, update, and delete records. Thanks to Valuelistenablebuilder, all changes are reflected in real time.

Final Thoughts on Offline Data Storage in Flutter Using Hive

In this tutorial, we learned how to:

  • Setup Hive in a Flutter app
  • Create a TypeAdapter with build_runner
  • Perform full CRUD operations: Add, View, Update, Delete
  • Build a modern UI using ValueListenableBuilder

Hive offers a blazing-fast, secure, and simple solution for local data storage, making it one of the best options for offline-first Flutter apps. Whether targeting mobile, web, or desktop, Hive is an excellent choice for smooth and efficient offline data handling.

If building production-ready apps, consider exploring advanced features like encrypted boxes, lazy boxes, or custom keys. Hive has you covered.

Picture of Sushma Akula

Sushma Akula

I'm Sushma Akula, a Flutter Junior Developer passionate about building seamless, cross-platform mobile apps with intuitive UI/UX. I love solving real-world problems and exploring the dynamic world of mobile and open-source tech

Get a free quote