Flutter – Store Data in Hive Local Database
Last Updated :
22 Apr, 2025
Hive is a data storage system on our phone where we can store data in boxes. We can store an integer, string, list of strings, Boolean, double, models, integers, etc., in Hive. Now, let us discuss where we can implement these. The first way we can use this is to save the user information user is logged in or not, and any ID or user details, so that users don’t have to log in again whenever a user opens that app. You can also store bigger data, but it will be stored for a particular device only. Hive is a NoSQL server where you can store a maximum amount of data in any form.
Difference Between Hive and SharedPreferences
Hive
| Shared Preferences
|
---|
Store Maximum data in it
| Limited to storing smaller data
|
Store Data in any type of data type
| Limited to some data types
|
Useful for storing larger data
| Useful for storing small data
|
Both work well. It’s up to your requirement to choose which one is best suitable for you.
For Shared Preferences, you can refer to this amazing article Flutter- SharedPreferences.
Step-by-Step Implementation
Step 1: Create a new Flutter Application
Create a new Flutter application using the command Prompt. To create a new app, write thefollowing,w command and run it.
flutter create app_name
To know more about it refer this article: Creating a Simple Application in Flutter.
Step 2: Adding the Dependency
To add the dependency to the pubspec.yaml file, add hive_flutter as a dependency in the dependencies part of the pubspec.yaml file, as shown below:
Dart
dependencies:
flutter:
sdk: flutter
hive_flutter: ^1.1.0
Now run the below command in the terminal.
flutter pub get
Or
Run the below command in the terminal.
flutter pub add hive_flutter
Step 3: File Structure
We will be using this File Structure in our Application.

Step 4: Initialize the Hive Box
Initialize the hive box, that we are going to use for storing the data.
Dart
Future main() async {
// It is used so that void main function
// can be intiated after successfully
// intialization of data
WidgetsFlutterBinding.ensureInitialized();
// To intialise the hive database
await Hive.initFlutter();
runApp(const MyApp());
}
Step 5: Open the Hive Box
Open the Hive Box in the main function
Dart
Future main() async {
// It is used so that void main function can
// be intiated after successfully intialization of data
WidgetsFlutterBinding.ensureInitialized();
// To intialise the hive database
await Hive.initFlutter();
// To open the user hive box
await Hive.openBox(userHiveBox);
runApp(const MyApp());
}
Step 6: Working with main.dart
main.dart:
Dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_geeks/Hive_box_const.dart';
import 'package:flutter_geeks/HomeScreen.dart';
import 'package:hive_flutter/hive_flutter.dart';
Future main() async {
// It is used so that void main function can
// be intiated after successfully intialization of data
WidgetsFlutterBinding.ensureInitialized();
// To intialise the hive database
await Hive.initFlutter();
// To open the user hive box
await Hive.openBox(userHiveBox);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen()
);
}
}
Step 7: Name HiveBox
Write all your HiveBox names in one file as mentioned below.
Dart
// Constant Name of Box where we will store details of user
const String userHiveBox="User Box";
Step 8: Working With Hive_functions
For better coding and understanding, we will write all the Hive Functions in one class as a separate file named Hive_functions.dart.
Dart
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive_flutter_templates/hive_box_constant.dart';
class HiveFunctions {
// Box which will use to store the things
static final userBox = Hive.box(userHiveBox);
}
Now we will add all the hive functions in the file named as hive_functions.dart
1. Create:
This will create the box or add the data to box.
Dart
// Create or add single data in hive
static createUser(Map data) {
userBox.add(data);
}
// Create or add multiple data in hive
static addAllUser(List data) {
userBox.addAll(data);
}
2. Read:
To read the data you have stored.
Dart
// Get All data stored in hive
static List getAllUsers() {
final data = userBox.keys.map((key) {
final value = userBox.get(key);
return {"key": key, "name": value["name"], "email": value['email']};
}).toList();
return data.reversed.toList();
}
// Get data for particular user in hive
static Map getUser(int key) {
return userBox.get(key);
}
3. Update:
Update the data that is already store.
Dart
// update data for particular user in hive
static updateUser(int key, Map data) {
userBox.put(key, data);
}
4. Delete:
Delete the data that is already stored.
Dart
// delete data for particular user in hive
static deleteUser(int key) {
return userBox.delete(key);
}
// delete data for particular user in hive
static deleteAllUser(int key) {
return userBox.deleteAll(userBox.keys);
}
Hive_functions.dart:
Dart
import 'package:flutter_geeks/Hive_box_const.dart';
import 'package:hive_flutter/hive_flutter.dart';
class HiveFunctions {
// Box which will use to store the things
static final userBox = Hive.box(userHiveBox);
// Create or add single data in hive
static createUser(Map data) {
userBox.add(data);
}
// Create or add multiple data in hive
static addAllUser(List data) {
userBox.addAll(data);
}
// Get All data stored in hive
static List getAllUsers() {
final data =
userBox.keys.map((key) {
final value = userBox.get(key);
return {"key": key, "name": value["name"], "email": value['email']};
}).toList();
return data.reversed.toList();
}
// Get data for particular user in hive
static Map getUser(int key) {
return userBox.get(key);
}
// update data for particular user in hive
static updateUser(int key, Map data) {
userBox.put(key, data);
}
// delete data for particular user in hive
static deleteUser(int key) {
return userBox.delete(key);
}
// delete data for particular user in hive
static deleteAllUser(int key) {
return userBox.deleteAll(userBox.keys);
}
}
Step 9: Working With HomeScreen
On the first screen I will add 1 floating action button will add value to hive database and will have list where list which will show the saved value in hive and in that list tile there will be two button for edit and delete items/users and 1 variable for list stored in database.
HomeScreen.dart:
Dart
import 'package:flutter/material.dart';
import 'package:hive_flutter_templates/hive_functions.dart';
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
// Local Variable Where we save
// the hive data of current context
List myHiveData = [];
// TextFields' controllers for adding or updating data
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
// To Update the data from Hive in local variable
getHiveData() {
myHiveData = HiveFunctions.getAllUsers();
setState(() {});
}
@override
void initState() {
super.initState();
// Update the initial data
// when page is loading
getHiveData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("CRUD Operations"),
actions: [
// To refreah the Data stored in Hive
IconButton(
onPressed: () {
getHiveData();
},
icon: const Icon(Icons.refresh))
],
),
// To add or create the data in Hive
floatingActionButton: FloatingActionButton.extended(
label: const Text("Add Data"),
icon: const Icon(Icons.add),
onPressed: () {
showForm(null);
}),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: myHiveData.isEmpty // To show when no data is stored
? const Center(
child: Text(
"No Data is Stored",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
))
// To show when data is stored
: Column(
children: List.generate(myHiveData.length, (index) {
final userData = myHiveData[index];
return Card(
child: ListTile(
title: //Show Name of user stored in data base
Text("Name : ${userData["name"]}"),
subtitle: //Show Email of user stored in data base
Text("Email : ${userData["email"]}"),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
// To edit the data stored
IconButton(
onPressed: () {
showForm(userData["key"]);
},
icon: const Icon(Icons.edit)),
// To delete the data stored
IconButton(
onPressed: () {
HiveFunctions.deleteUser(userData["key"]);
// To refreah the Data stored in Hive after deletion
getHiveData();
},
icon: const Icon(Icons.delete)),
],
),
),
);
}).toList()),
));
}
// dialog box to create or update the data in hive
void showForm(int? itemKey) async {
// itemKey == null -> create new item
// itemKey != null -> update an existing item
if (itemKey != null) {
// To find the existing item in our local database
final existingItem =
myHiveData.firstWhere((element) => element['key'] == itemKey);
_nameController.text = existingItem['name'];
_emailController.text = existingItem['email'];
}
showModalBottomSheet(
context: context,
elevation: 5,
isScrollControlled: true,
builder: (_) => Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
top: 15,
left: 15,
right: 15),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Text(
itemKey == null ? 'Create New' : 'Update',
style: const TextStyle(
fontSize: 22, fontWeight: FontWeight.w600),
)),
TextField(
controller: _nameController,
decoration: const InputDecoration(hintText: 'Name'),
),
const SizedBox(
height: 10,
),
TextField(
controller: _emailController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(hintText: 'Email'),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
// Save new item
if (itemKey == null) {
HiveFunctions.createUser({
"email": _emailController.text,
"name": _nameController.text
});
}
// update an existing item
if (itemKey != null) {
HiveFunctions.updateUser(itemKey, {
"email": _emailController.text,
"name": _nameController.text
});
}
// Clear the text fields
_nameController.text = '';
_emailController.text = '';
Navigator.of(context).pop(); // Close the bottom sheet
// To refresh the Data stored in Hive after updation
getHiveData();
},
child: Text(itemKey == null ? 'Create New' : 'Update'),
),
const SizedBox(
height: 15,
)
],
),
));
}
}
Here, we are calling different functions on different onClick and initstate.
- We will call the getAll function in initState.
- Show the form function in the floating action button.
- Update the function in the edit button.
- Delete function in the delete button.
Complete Source Code
There are multiple files of dart used in our Application as mentioned below:
HomeScreen.dart
import 'package:flutter/material.dart';
import 'package:flutter_geeks/Hive_functions.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
// Local Variable Where we save
// the hive data of current context
List myHiveData = [];
// TextFields' controllers for adding or updating data
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
// To Update the data from Hive in local variable
getHiveData() {
myHiveData = HiveFunctions.getAllUsers();
setState(() {});
}
@override
void initState() {
super.initState();
// Update the initial data
// when page is loading
getHiveData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("CRUD Operations"),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
actions: [
// To refreah the Data stored in Hive
IconButton(
onPressed: () {
getHiveData();
},
icon: const Icon(Icons.refresh),
),
],
),
// To add or create the data in Hive
floatingActionButton: FloatingActionButton.extended(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
label: const Text("Add Data"),
icon: const Icon(Icons.add),
onPressed: () {
showForm(null);
},
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child:
myHiveData
.isEmpty // To show when no data is stored
? const Center(
child: Text(
"No Data is Stored",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
)
// To show when data is stored
: Column(
children:
List.generate(myHiveData.length, (index) {
final userData = myHiveData[index];
return Card(
child: ListTile(
title: //Show Name of user stored in data base
Text("Name : ${userData["name"]}"),
subtitle: //Show Email of user stored in data base
Text("Email : ${userData["email"]}"),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
// To edit the data stored
IconButton(
onPressed: () {
showForm(userData["key"]);
},
icon: const Icon(Icons.edit),
),
// To delete the data stored
IconButton(
onPressed: () {
HiveFunctions.deleteUser(userData["key"]);
// To refreah the Data stored in Hive after deletion
getHiveData();
},
icon: const Icon(Icons.delete),
),
],
),
),
);
}).toList(),
),
),
);
}
// dialog box to create or update the data in hive
void showForm(int? itemKey) async {
// itemKey == null -> create new item
// itemKey != null -> update an existing item
if (itemKey != null) {
// To find the existing item in our local database
final existingItem = myHiveData.firstWhere(
(element) => element['key'] == itemKey,
);
_nameController.text = existingItem['name'];
_emailController.text = existingItem['email'];
}
showModalBottomSheet(
context: context,
elevation: 5,
isScrollControlled: true,
builder:
(_) => Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
top: 15,
left: 15,
right: 15,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Text(
itemKey == null ? 'Create New' : 'Update',
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w600,
),
),
),
TextField(
controller: _nameController,
decoration: const InputDecoration(hintText: 'Name'),
),
const SizedBox(height: 10),
TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(hintText: 'Email'),
),
const SizedBox(height: 20),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
onPressed: () async {
// Save new item
if (itemKey == null) {
HiveFunctions.createUser({
"email": _emailController.text,
"name": _nameController.text,
});
}
// update an existing item
if (itemKey != null) {
HiveFunctions.updateUser(itemKey, {
"email": _emailController.text,
"name": _nameController.text,
});
}
// Clear the text fields
_nameController.text = '';
_emailController.text = '';
Navigator.of(context).pop(); // Close the bottom sheet
// To refresh the Data stored in Hive after updation
getHiveData();
},
child: Text(itemKey == null ? 'Create New' : 'Update'),
),
const SizedBox(height: 15),
],
),
),
);
}
}
Hive_functions.dart
import 'package:flutter_geeks/Hive_box_const.dart';
import 'package:hive_flutter/hive_flutter.dart';
class HiveFunctions {
// Box which will use to store the things
static final userBox = Hive.box(userHiveBox);
// Create or add single data in hive
static createUser(Map data) {
userBox.add(data);
}
// Create or add multiple data in hive
static addAllUser(List data) {
userBox.addAll(data);
}
// Get All data stored in hive
static List getAllUsers() {
final data =
userBox.keys.map((key) {
final value = userBox.get(key);
return {"key": key, "name": value["name"], "email": value['email']};
}).toList();
return data.reversed.toList();
}
// Get data for particular user in hive
static Map getUser(int key) {
return userBox.get(key);
}
// update data for particular user in hive
static updateUser(int key, Map data) {
userBox.put(key, data);
}
// delete data for particular user in hive
static deleteUser(int key) {
return userBox.delete(key);
}
// delete data for particular user in hive
static deleteAllUser(int key) {
return userBox.deleteAll(userBox.keys);
}
}
Hive_box_const.dart
// Constant Name of Box where we will store details of user
const String userHiveBox="User Box";
main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_geeks/Hive_box_const.dart';
import 'package:flutter_geeks/HomeScreen.dart';
import 'package:hive_flutter/hive_flutter.dart';
Future main() async {
// It is used so that void main function can
// be intiated after successfully intialization of data
WidgetsFlutterBinding.ensureInitialized();
// To intialise the hive database
await Hive.initFlutter();
// To open the user hive box
await Hive.openBox(userHiveBox);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen()
);
}
}
Output:
Commonly Faced Errors with Solutions
There are few commonly faced errors with Hive by users as mentioned below.
1. Unhandled Exception: HiveError: You need to initialize Hive or provide a path to store the box.
Solution: You forgot to initialize the hive in the main function
2. The following HiveError was thrown while building Builder: Box not found. Did you forget to call Hive.openBox()?
Solution: You forgot to open the box.
3. Unhandled exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/hive_flutter)
Solution: Uninstall the application and reinstall it.
Similar Reads
Flutter - Realtime Database in Firebase
Firebase helps developers to build and run their apps successfully; its backend is developed by Google. Firebase is very easy to use for beginners; it provides many functionalities like Firebase Authentication, Cloud Firestore, Realtime Database, Firebase Storage, etc, which help to build and optimi
6 min read
Flutter - Read and Write Data on Firebase
Firebase helps developers to manage their mobile apps easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from Firebase. Follow the 3-step proce
4 min read
Building a Movie Database App in Flutter
In this tutorial, we'll create a Flutter app that fetches movie data from an API, displays details such as ratings and reviews, and allows users to save their favorite movies locally using SQLite. This Application will demonstrate API integration, state management, and local data persistence. Applic
12 min read
DataTable in Flutter
A DataTable is a material design used to display data on a table or in rows and columns. A Data table is used to show the data which have columns and rows as child, a Column is used to set the name of the column, and a Row is used to set the values of the columns. Any column in a DataTable can be so
2 min read
Flutter - Deleting Data On The Internet
In this article, we will explore the process of deleting data on the internet. Before deleting data on the internet, we will fetch the data first and then will delete the data. Steps to implement Deleting Data on the InternetStep 1 : Create a new flutter applicationCreate a new Flutter application u
4 min read
Flutter - Create TypeAdapters in Hive
Flutter is open source framework from which we can create cross-platform applications with a single codebase. Hive is a local device storage that stores data in your phone storage. We store user profiles and tokens whether they are logged in or not like that thing. To deeply understand what hive ple
3 min read
Flutter - Read JSON Data from Assets Folder
A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. We will learn how to read the data already stored in your project folder in your app with
3 min read
How to Add Firebase to Flutter App?
Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and more securely. No programming is required on the Firebase side which makes it easy to use its features more efficiently. It provides services to Andr
3 min read
How to Add Firebase into Flutter in a New Way?
Recently Firebase give another option for adding Firebase to Flutter and It is only made for Flutter, As of now we add firebase using the android option for flutter but now we can add using the flutter option that is recently updated by Flutter. Here you can find how to add firebase as an Android in
2 min read
Flutter - Sending Data To The Internet
Interacting with the Internet is crucial for most apps to function. In Flutter, sending data to the internet is one of them, and the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. Steps to Implement Sending Data to the InternetStep 1
5 min read