DEV Community

vmodal_ai
vmodal_ai

Posted on

Mastering Hive in Flutter: A Step by Step Beginner's Guide to Fast Local Storage

Introduction

When building a Flutter application, you'll often need to store data on the user's device. For example:

  • Saving user preferences
  • Storing login information
  • Caching API responses
  • Creating offline applications
  • Building note-taking or to-do apps

While there are several local storage solutions available, Hive is one of the fastest and easiest local storage for Flutter developers.

In this tutorial, you'll learn Hive from scratch by building a simple example. No prior database knowledge is required.


What is Hive?

Hive is a lightweight, NoSQL database written entirely in Dart. It stores data directly on the device, making it perfect for Flutter applications.

Why use Hive?

  • Extremely fast
  • Works offline
  • No native platform code required
  • Simple API
  • Easy to learn
  • Great for small and medium-sized applications

Think of Hive as a collection of boxes where each box stores your application's data.

Hive
 ├── User Box
 ├── Settings Box
 ├── Notes Box
 └── Products Box
Enter fullscreen mode Exit fullscreen mode

Each Box is similar to a table in traditional databases.


Step 1: Create a Flutter Project

Create a new Flutter project.

flutter create hive_demo
Enter fullscreen mode Exit fullscreen mode

Open the project.

cd hive_demo
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Hive

Open pubspec.yaml and add the following packages.

dependencies:
  flutter:
    sdk: flutter

  hive: ^2.2.3
  hive_flutter: ^1.1.0
Enter fullscreen mode Exit fullscreen mode

Then install them.

flutter pub get
Enter fullscreen mode Exit fullscreen mode

Step 3: Initialize Hive

Before using Hive, initialize it inside main().

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Hive.initFlutter();

  await Hive.openBox('settings');

  runApp(const MyApp());
}
Enter fullscreen mode Exit fullscreen mode

Here we open a box called settings.


Step 4: Understanding Boxes

A Box is where Hive stores data.

Imagine this box:

Settings Box

theme       -> dark
username    -> Alex
loggedIn    -> true
Enter fullscreen mode Exit fullscreen mode

Keys are on the left.

Values are on the right.


Step 5: Save Data

Saving data is incredibly simple.

var box = Hive.box('settings');

box.put('username', 'John');
box.put('age', 25);
box.put('isPremium', true);
Enter fullscreen mode Exit fullscreen mode

You can store:

  • String
  • int
  • double
  • bool
  • List
  • Map

Step 6: Read Data

Reading data is just as easy.

var box = Hive.box('settings');

String name = box.get('username');

print(name);
Enter fullscreen mode Exit fullscreen mode

Output

John
Enter fullscreen mode Exit fullscreen mode

You can also provide a default value.

String name = box.get(
  'username',
  defaultValue: 'Guest',
);
Enter fullscreen mode Exit fullscreen mode

If the key doesn't exist, Hive returns Guest.


Step 7: Update Existing Data

Updating is exactly the same as saving.

box.put('username', 'Alice');
Enter fullscreen mode Exit fullscreen mode

The previous value is replaced automatically.

Before

username -> John
Enter fullscreen mode Exit fullscreen mode

After

username -> Alice
Enter fullscreen mode Exit fullscreen mode

Step 8: Delete Data

Delete a single value.

box.delete('username');
Enter fullscreen mode Exit fullscreen mode

Delete everything.

box.clear();
Enter fullscreen mode Exit fullscreen mode

Step 9: Build a Simple Example

Let's create a simple app that stores a user's name.

UI

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final controller = TextEditingController();

  final box = Hive.box('settings');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hive Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: controller,
              decoration: const InputDecoration(
                labelText: 'Enter your name',
              ),
            ),

            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: () {
                box.put('username', controller.text);

                setState(() {});
              },
              child: const Text('Save'),
            ),

            const SizedBox(height: 30),

            Text(
              'Saved Name: ${box.get('username', defaultValue: "None")}',
              style: const TextStyle(fontSize: 20),
            )
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Run the app.

Enter a name.

Press Save.

Close the app and reopen it.

You'll notice the name is still there because Hive stores it locally on the device.


Step 10: Listen for Changes Automatically

Instead of calling setState() manually, Hive can rebuild the UI whenever the data changes.

ValueListenableBuilder(
  valueListenable: box.listenable(),
  builder: (context, box, _) {
    return Text(
      box.get(
        'username',
        defaultValue: 'Guest',
      ),
    );
  },
)
Enter fullscreen mode Exit fullscreen mode

Whenever the value changes, the widget updates automatically.


Step 11: Store Lists

Hive can store lists easily.

box.put(
  'fruits',
  [
    'Apple',
    'Banana',
    'Orange'
  ],
);
Enter fullscreen mode Exit fullscreen mode

Retrieve them.

List fruits = box.get('fruits');

print(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

[Apple, Banana, Orange]
Enter fullscreen mode Exit fullscreen mode

Step 12: Store Maps

You can also store maps.

box.put(
  'user',
  {
    'name': 'John',
    'age': 25,
    'city': 'London'
  },
);
Enter fullscreen mode Exit fullscreen mode

Retrieve them.

Map user = box.get('user');

print(user['name']);
Enter fullscreen mode Exit fullscreen mode

Output

John
Enter fullscreen mode Exit fullscreen mode

Common Hive Operations

Task Code
Open Box await Hive.openBox('settings');
Save Data box.put('key', value);
Read Data box.get('key');
Update Data box.put('key', newValue);
Delete Item box.delete('key');
Delete All box.clear();
Check Key Exists box.containsKey('key');
Get All Keys box.keys
Get All Values box.values

When Should You Use Hive?

Hive is an excellent choice when your app needs:

  • User settings
  • Theme preferences
  • Offline storage
  • Shopping carts
  • Notes
  • To-do lists
  • Cached API responses
  • Authentication tokens

For large-scale relational data with complex queries, consider a database such as SQLite or Drift instead.


Final Thoughts

Hive is one of the simplest local storage you can learn as a Flutter developer. With just a few methods—put(), get(), delete(), and clear()—you can build applications that work even without an internet connection.

As your projects grow, you can also use Hive to store custom Dart objects, encrypt data for added security, and organise information into multiple boxes. Mastering these basics gives you a solid foundation for building fast, responsive, and offline-capable Flutter applications.

Happy coding!

Top comments (0)