A Beginner's Guide to Using Hive with Models in Flutter
How to Use Hive for Storing and Retrieving Data in Flutter with Custom Models
Introduction
In mobile app development, especially with Flutter, local storage plays a crucial role in persisting data. One of the most popular solutions for local data storage in Flutter is Hive, a lightweight and fast NoSQL database that provides a simple API for storing and retrieving data.
In this blog, we’ll walk through how to use Hive with custom models in Flutter. We’ll demonstrate how to store and retrieve data of a custom model (User
), using Hive's built-in functionality. We will also discuss the importance of null safety when dealing with data retrieval.
Setting Up Hive in Flutter
Before diving into the code, let’s first ensure that Hive is set up in your Flutter project. If you haven’t already, you’ll need to add the Hive package and the Hive Flutter package to your pubspec.yaml
:
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
hive: ^2.0.0
hive_flutter: ^1.1.0
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^4.0.0
build_runner: ^2.0.0
hive_generator: ^1.1.0
1. Create Your Custom Model Class (User
)
Before storing data in Hive, we need to create a custom data model. In this example, we’re going to use a simple User
class with name
and age
fields.
import 'package:hive/hive.dart';
part 'user.g.dart';
@HiveType(typeId: 0)
class User {
@HiveField(0)
final String name;
@HiveField(1)
final int age;
User(this.name, this.age);
}
Here’s what’s happening in the code:
@HiveType(typeId: 0)
: This annotation tells Hive that we are defining a custom type and gives it a unique ID. Each model class needs to have a uniquetypeId
.@HiveField()
: Each field in the model is annotated with@HiveField
to define its number. These numbers help Hive identify which data is being serialized or deserialized.
2. Generate the Adapter
To let Hive know how to serialize and deserialize the User
class, we need to generate a type adapter using the hive_generator
package. Run the following command to generate the adapter:
flutter packages pub run build_runner build
This will generate a file called user.g.dart
that contains the UserAdapter
for the User
model. Now Hive can store and retrieve User
objects.
3. Initialize Hive in Your Flutter App
Next, we need to initialize Hive in the main function and register the UserAdapter
.
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'model/user.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Hive
await Hive.initFlutter();
// Register User Adapter
Hive.registerAdapter(UserAdapter());
// Open the box to store User data
await Hive.openBox<User>('userBox');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Hive TypeAdapter Example')),
body: Center(
child: ElevatedButton(
onPressed: () async {
var userBox = Hive.box<User>('userBox');
// Create and add User object
var user = User('John Doe', 30);
await userBox.add(user);
// Retrieve User object
User? retrievedUser = userBox.getAt(0); // Notice the '?' here
if (retrievedUser != null) {
print('User: ${retrievedUser.name}, Age: ${retrievedUser.age}');
} else {
print('No user found.');
}
},
child: Text('Save and Retrieve Data'),
)
,
),
),
);
}
}
4. Explanation of the Code
Initializing Hive
This initializes Hive for use with Flutter. You need this setup before you can interact with Hive boxes.
Registering the Adapter
Here, we’re registering the adapter for the User
class, which is generated in the user.g.dart
file. This step ensures that Hive knows how to store and retrieve User
objects.
Opening a Box
This opens a box called 'userBox'
, which will store all the User
objects. If the box doesn’t exist, it will be created.
Saving a User
Object
User
object and stores it in the userBox
. The add()
method stores the object at the next available index.This retrieves the first User
object in the box. Notice that we use User?
as the type because Hive’s getAt()
method can return null
if the object at the specified index doesn’t exist.
5. Handling Null Safety
In this code, we used null safety to handle the case where the box might not contain any data. Since getAt(0)
returns a nullable User?
, we check if the object is null
before attempting to access its properties.
// Retrieve User object
User? retrievedUser = userBox.getAt(0); // Notice the '?' here
if (retrievedUser != null) {
print('User: ${retrievedUser.name}, Age: ${retrievedUser.age}');
} else {
print('No user found.');
}
This ensures that our code doesn’t throw an exception when no data is found at the specified index.
6. Running the App
When you run this app, you’ll see a button labeled "Save and Retrieve Data". When pressed, it will:
- Save a new
User
object (John Doe
, 30) to the box. - Retrieve the first
User
object from the box and print the details in the console.
Conclusion
Hive is a powerful, fast, and easy-to-use local storage solution for Flutter apps. In this blog, we learned how to:
- Set up Hive in Flutter.
- Define a custom data model (
User
) and register its adapter. - Store and retrieve custom objects in Hive.
- Handle nullable values properly using null safety.
This setup is perfect for small to medium-sized apps where you need to store simple data locally. Hive is highly efficient, even with large datasets, making it a great choice for persistent storage in Flutter.
Let us know in the comments if you have any questions or need further assistance!
github. https://github.com/Sutharpraveen/hive
Great!
ReplyDelete