Enable Dark Mode!
how-to-use-hive-to-store-and-retrieve-data-in-a-flutter-application.jpg
By: Farhana Jahan PT

How to Use Hive to Store & Retrieve Data in a Flutter Application

Technical

Effective data management is essential to ensuring a good user experience in mobile app development. Flutter, Google's UI toolkit for crafting natively compiled applications, offers a range of solutions for handling data, but one of the most powerful and lightweight options is the Hive package.

In this blog, we'll explore how to use Hive to store and retrieve data in a Flutter application.

Let's add ID, name, and description to Hive for storage. Additionally, we'll include any other relevant records that you want to store. We'll then retrieve these values from Hive as needed.

For that, firstly we need to set up Hive for local storage as per below code:

import 'package:hive/hive.dart';
part 'group.g.dart';
@HiveType(typeId: 0)
class Group extends HiveObject {
  @HiveField(0)
  final int id;
  @HiveField(1)
  final String title;
  @HiveField(2)
  final String description;
  Group({required this.id, required this.title, required this.description});
}

You can include other records that you want to store. 

After setup hive, run the following commands to generate the Hive adapter for your model. Before executing the command, you need to add build_runner: ^2.1.11 to dependency at yaml file

flutter packages pub run build_runner build

This will generate the group.g.dart file with the necessary serialization code. The corresponding group.g.dart file for setting up Hive is shown below, and it is automatically generated.

// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'group.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class GroupAdapter extends TypeAdapter<Group> {
  @override
  final int typeId = 0;
  @override
  Group read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Group(
      id: fields[0] as int,
      title: fields[1] as String,
      description: fields[2] as String,
    );
  }
  @override
  void write(BinaryWriter writer, Group obj) {
    writer
      ..writeByte(3)
      ..writeByte(0)
      ..write(obj.id)
      ..writeByte(1)
      ..write(obj.title)
      ..writeByte(2)
      ..write(obj.description);
  }
  @override
  int get hashCode => typeId.hashCode;
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is GroupAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

To use Hive, you need to initialize it in your main function. This is typically done in main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDir = await getApplicationDocumentsDirectory();
  Hive.init(appDocumentDir.path);
  Hive.registerAdapter(GroupAdapter());
  await Hive.openBox<Group>('groups');
  runApp(MyApp());
}

Now use Hive for retrieving data.

In our GroupList widget, we’ll open the Hive box and populate it with sample data if it’s empty. We will use ValueListenableBuilder to listen for changes and update the UI accordingly.

The code for it is given below:

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'hive_offline/group.dart';
class GroupList extends StatefulWidget {
  const GroupList({super.key, required this.title});
  final String title;
  @override
  State<GroupList> createState() => GroupListState();
}
class GroupListState extends State<GroupList> {
  late Box<Group> box;
  @override
  void initState() {
    super.initState();
    openBox();
  }
  Future<void> openBox() async {
    box = await Hive.openBox<Group>('groups');
    if (box.isEmpty) {
      box.add(Group(id: 1, title: 'Flutter', description: 'Flutter group'));
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ValueListenableBuilder(
        valueListenable: box.listenable(),
        builder: (context, Box<Group> box, widget) {
          return ListView.builder(
            itemCount: box.length,
            itemBuilder: (context, index) {
              final group = box.getAt(index) as Group;
              return ListTile(
                title: Text(group.title),
                subtitle: Text(group.description),
                leading: CircleAvatar(
                  child: Text('${group.id}'),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

You can store the data in the local database using the code provided, allowing you to access and utilize the stored information as needed.

Integrating Hive into your Flutter application provides a simple and efficient way to manage local storage. By defining models, initializing Hive, and using ValueListenableBuilder, you can easily store and retrieve data offline.

To read more about How to Create Bottom Bar Navigation in Flutter, refer to our blog How to Create Bottom Bar Navigation in Flutter.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message