On this page16 sections
Lecture 002 — Boxes: put, get & delete
| Category | 1 — Hive Basics |
| Lecture | 002 of 007 |
| Estimated video length | 20 min |
| Target | Flutter 3.44 · Dart 3.12 · hive 2.2 |
| Level | Beginner |
| Video | Part 1 — Introduction, Setup, Model Adapters & Manager Classes |
| Source code | GitHub — 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
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 withget, remove withdelete - Use
containsKey,keys,values,lengthandclear - Tell
put(your own key) fromadd(auto number)
1. Open a Box
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
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
await box.delete('age'); // remove one key
await box.clear(); // remove everything in the box4. Looking Inside
| Call | Gives |
|---|---|
box.containsKey('x') | true / false |
box.keys | all keys |
box.values | all values |
box.length | number of entries |
box.isEmpty | no entries |
5. add — Auto Keys
final key = await box.add('first note'); // key 0
await box.add('second note'); // key 1add 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
final names = await Hive.openBox<String>('names');
names.put('a', 'Ali');
// names.put('b', 5); // compile error: int is not a StringA typed box catches mistakes at compile time. Box<DataObjects> will do this for our class.
Code Examples
Example 1 — A Remembered Name
// 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, beforerunApp. - Use clear constant names for boxes and keys instead of repeating strings.
- Await
put/deletewhen 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
- How do you read a key with a fallback? 2. What is the difference between
putandadd? - What does
cleardo? 4. Why useBox<String>?
Practice Answers
box.get('k', defaultValue: x).putuses a key you choose and overwrites it;addcreates the next integer key.- Deletes every entry in the box.
- The compiler rejects values that are not
String.
Key Takeaways
openBoxonce;Hive.boxanywhere after.putsaves or replaces,getreads,deleteremoves.- A change in a box does not rebuild widgets by itself.