On this page17 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Open a Box
  5. 2. put and get
  6. 3. delete and clear
  7. 4. Looking Inside
  8. 5. add: Auto Keys
  9. 6. Typed Boxes
  10. Code Examples
  11. Common Beginner Mistakes
  12. Best Practices
  13. Mini Challenge
  14. Practice Questions
  15. Practice Answers
  16. Key Takeaways
  17. Full Code (Copy-Paste Reference)

Lecture 002: Boxes: put, get & delete

Category1: Hive Basics
Lecture002 of 007
Estimated video length20 min
TargetFlutter 3.44 · Dart 3.12 · hive 2.2
LevelBeginner
VideoPart 1: Introduction, Setup, Model Adapters & Manager Classes
Source codeGitHub: urraan_hive_final_code

Before we save our own classes, we save the simplest things, text and numbers, to learn the four box actions every Hive app uses: open, put, get, delete.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lecture 001: project with hive and hive_flutter, and Hive.initFlutter() in main.


Connection With Previous Lectures

Lecture 001 installed Hive. Now we use it: a box is opened once, then used like a Map.


Learning Objectives

  • Open a box with Hive.openBox
  • Save with put, read with get, remove with delete
  • Use containsKey, keys, values, length and clear
  • Tell put (your own key) from add (auto number)

1. Open a Box

dart
final box = await Hive.openBox('settings');

Opening reads the box file from disk. Do it once at startup: it is async. Afterwards, get the same box anywhere with Hive.box('settings'): no await.

2. put and get

dart
box.put('username', 'Zayan');
box.put('age', 21);

final name = box.get('username');             // 'Zayan'
final missing = box.get('city');              // null
final withDefault = box.get('city', defaultValue: 'Karachi');

put adds the key or replaces it: there is no separate "update". put is synchronous for reading but returns a Future; awaiting it guarantees the data reached the disk.

3. delete and clear

dart
await box.delete('age');   // remove one key
await box.clear();         // remove everything in the box

4. Looking Inside

CallGives
box.containsKey('x')true / false
box.keysall keys
box.valuesall values
box.lengthnumber of entries
box.isEmptyno entries

5. add: Auto Keys

dart
final key = await box.add('first note');   // key 0
await box.add('second note');              // key 1

add picks the next integer key. Our contacts app uses put with its own key so a record can be found and updated later.

6. Typed Boxes

dart
final names = await Hive.openBox<String>('names');
names.put('a', 'Ali');
// names.put('b', 5);   // compile error: int is not a String

A typed box catches mistakes at compile time. Box<DataObjects> will do this for our class.


Code Examples

Example 1: A Remembered Name

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  await Hive.openBox('settings');
  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),
      home: const HomeScreen(),
    );
  }
}

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final box = Hive.box('settings');
  final controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final saved = box.get('username', defaultValue: 'nobody');
    return Scaffold(
      appBar: AppBar(title: const Text('Remembered name')),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            Text('Saved name: $saved', style: const TextStyle(fontSize: 22)),
            TextField(controller: controller),
            Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    box.put('username', controller.text);
                    setState(() {});
                  },
                  child: const Text('Save'),
                ),
                const SizedBox(width: 10),
                OutlinedButton(
                  onPressed: () {
                    box.delete('username');
                    setState(() {});
                  },
                  child: const Text('Delete'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Type a name, press Save, close the app completely and reopen it: the name is still there. That is the whole point of Hive.


Common Beginner Mistakes

1. Hive.box('x') before openBox: throws "Box not found. Did you forget to call Hive.openBox()?". Open every box in main.

2. Mixing a typed and untyped open: if you open Hive.openBox<String>('a') you must also use Hive.box<String>('a').

3. Expecting the UI to refresh: a put changes the box, not the screen. We called setState here; Lecture 005 replaces that with ValueListenableBuilder.


Best Practices

  • Open all boxes in main, before runApp.
  • Use clear constant names for boxes and keys instead of repeating strings.
  • Await put/delete when the next step depends on the data being saved.

Mini Challenge

Add a second field, age, saved as an int. Show both, and make Delete remove both keys.


Practice Questions

  1. How do you read a key with a fallback? 2. What is the difference between put and add?
  2. What does clear do? 4. Why use Box<String>?

Practice Answers

  1. box.get('k', defaultValue: x).
  2. put uses a key you choose and overwrites it; add creates the next integer key.
  3. Deletes every entry in the box.
  4. The compiler rejects values that are not String.

Key Takeaways

  • openBox once; Hive.box anywhere after.
  • put saves or replaces, get reads, delete removes.
  • A change in a box does not rebuild widgets by itself.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture. Still one file.

lib/main.dart

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();

  // Opened once, here, before runApp - every screen can then use Hive.box('settings')
  // synchronously without awaiting it again.
  await Hive.openBox('settings');

  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),
      home: const HomeScreen(),
    );
  }
}

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // Already-open box - no await needed here, only when it was first opened in main().
  final box = Hive.box('settings');
  final controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // defaultValue covers the very first run, before anything has been saved.
    final saved = box.get('username', defaultValue: 'nobody');

    return Scaffold(
      appBar: AppBar(title: const Text('Remembered name')),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            Text('Saved name: $saved', style: const TextStyle(fontSize: 22)),
            TextField(controller: controller),
            Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    // put() both creates and overwrites - there is no separate "update".
                    box.put('username', controller.text);
                    setState(() {}); // box changes don't rebuild the UI by themselves
                  },
                  child: const Text('Save'),
                ),
                const SizedBox(width: 10),
                OutlinedButton(
                  onPressed: () {
                    box.delete('username');
                    setState(() {});
                  },
                  child: const Text('Delete'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Video lecture

Lecture 002 · 20 min