Flutter Hive database - Hive CRUD Operations

Last updated Jul 15, 2021


In this flutter example we will cover integrate Hive database to store local storage. Hive database is a very light weight database which will work very fast and easy to integrate in flutter applications.

In flutter we have different types of local storage options are there like Sharedpreferences and Sqlite Database

Hive will store the data in key/value pair structure, this will be more fast compare to shared preference, if we want to store more complex data then we have to go with flutter sqlite database.

 

Flutter How do i work with Hive database

 

So let's get started

 

Step 1: Create flutter application

Step 2: Add required dependencies

dependencies:
  flutter:
    sdk: flutter
  hive: ^2.0.4
dev_dependencies:
  hive_generator: ^1.1.0
  build_runner: ^2.0.6

 

Step 3: Import hive packages in dart file

import 'package:hive/hive.dart';

 

Step 4: Initialize Hive Database

To initialize hive database we need to execute this on main method before execute other functionalities

So we need to write hive initialization code in main method. Hive.init(directory.path) will be initialize the hive database at specific location.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Directory directory = await pathProvide.getApplicationDocumentsDirectory();
  Hive.init(directory.path);
  runApp(MyApp());
}

 

To work with hive we need to create model classes for the data storage. In this example we are handle student data so just create a model class Student. To tell the Hive database to this is my student class to store the student data, so we need to add hive meta info to the Student model

@HiveType(typeId: 1,adapterName: "StudentAdapter")
class Student{
  @HiveField(0)
  String name;

  @HiveField(1)
  String email;

  @HiveField(2)
  String mobile;

  Student({required this.name,required this.email,required this.mobile});
}

 

@HiveType will tell the information above the student table which contains two arguments typeId and adaptername.

The @HiveField tells the data to pass for each property.

 

Now we created Student model, then we need to tell hive to this is my model to handle the data of the students, for this we need to generate Adapter class for the student as "StudentAdapter"

To generate StudentAdapter we need to run below command in terminal

flutter packages pub run build_runner build

 

It will generate a file student.g.dart with below code

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'student.dart';

// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************

class StudentAdapter extends TypeAdapter<Student> {
  @override
  final int typeId = 1;

  @override
  Student read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Student(
      name: fields[0] as String,
      email: fields[1] as String,
      mobile: fields[2] as String,
    );
  }

  @override
  void write(BinaryWriter writer, Student obj) {
    writer
      ..writeByte(3)
      ..writeByte(0)
      ..write(obj.name)
      ..writeByte(1)
      ..write(obj.email)
      ..writeByte(2)
      ..write(obj.mobile);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is StudentAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

 

Now we need to add it hive by adding below line after initializing the hive

Hive.registerAdapter(StudentAdapter());

 

 

Step 5: Add Student data

To make any hive operations we need to create a Box by calling open() method on hive instance.

Student studentdata = new Student(
    name: getStName,
    email: getEmail,
    mobile: getMobile);
var box = await Hive.openBox<Student>('student');
box.add(studentdata);

 

Flutter Add data to Hive database

 

 

Fetch Students

final box = await Hive.openBox<Student>('student');
listStudents = box.values.toList();

 

Flutter Hive Database operations

 

 

Update Data with Hive

Student studentdata = new Student
( name: getStName, email: getEmail, mobile: getMobile);
var box = await Hive.openBox<Student>('student');
box.putAt(widget.position, studentdata);

 

 

Delete data from hive

final box = Hive.box<Student>('student');
box.deleteAt(position);

 

 

 

Complete code

main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_hive/screens/students_list.dart';
import 'package:flutter_hive/student.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as pathProvide;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Directory directory = await pathProvide.getApplicationDocumentsDirectory();
  Hive.init(directory.path);
  Hive.registerAdapter(StudentAdapter());
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.deepPurple,
      ),
      home: StudentListScreen(),
    );
  }
}

 

Add Student

import 'package:flutter/material.dart';
import 'package:flutter_hive/screens/students_list.dart';
import 'package:flutter_hive/student.dart';
import 'package:hive/hive.dart';

class AddOrUpdateStudent extends StatefulWidget{
  bool isEdit;
  int position=-1;
  Student? studentModel=null;

  AddOrUpdateStudent(this.isEdit, this.position,this.studentModel);

  @override
  State<StatefulWidget> createState() {

    return AddOrUpdateStudentState();
  }

}

class AddOrUpdateStudentState extends State<AddOrUpdateStudent>{
  TextEditingController controllerName = new TextEditingController();
  TextEditingController controllerEmail = new TextEditingController();
  TextEditingController controllerMobile = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    if (widget.isEdit) {
      controllerName.text = widget.studentModel!.name;
      controllerEmail.text = widget.studentModel!.email;
      controllerMobile.text = widget.studentModel!.mobile;
    }

    return SafeArea(
      child: Scaffold(
        appBar: AppBar(title :Text("Add/Update Student Data")),
          body: SingleChildScrollView(
            child: Container(
              margin: EdgeInsets.all(25),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text("Student Name:", style: TextStyle(fontSize: 18)),
                      SizedBox(width: 20),
                      Expanded(
                        child: TextField(controller: controllerName,
                          textInputAction: TextInputAction.next,
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 60),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text("Student Email:", style: TextStyle(fontSize: 18)),
                      SizedBox(width: 20),
                      Expanded(
                        child: TextField(
                            controller: controllerEmail,
                            textInputAction: TextInputAction.next,
                            keyboardType: TextInputType.emailAddress),
                      )
                    ],
                  ),
                  SizedBox(height: 60),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text("Student Mobile:", style: TextStyle(fontSize: 18)),
                      SizedBox(width: 20),
                      Expanded(
                        child: TextField(
                          controller: controllerMobile,
                          keyboardType: TextInputType.number,
                          textInputAction: TextInputAction.done,),
                      )
                    ],
                  ),
                  SizedBox(height: 100),
                  MaterialButton(
                    color: Colors.deepOrange,
                    child: Text("Submit",
                        style: TextStyle(color: Colors.white, fontSize: 18)),
                    onPressed: () async {
                      var getStName = controllerName.text;
                      var getEmail = controllerEmail.text;
                      var getMobile = controllerMobile.text;
                      if (getStName.isNotEmpty &
                      getEmail.isNotEmpty &
                      getMobile.isNotEmpty) {
                        Student studentdata = new Student(
                            name: getStName,
                            email: getEmail,
                            mobile: getMobile);

                        if (widget.isEdit) {
                          var box = await Hive.openBox<Student>('student');
                          box.putAt(widget.position, studentdata);
                        } else {
                          var box = await Hive.openBox<Student>('student');
                          box.add(studentdata);
                        }
                        Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(
                                builder: (_) => StudentListScreen()),
                                (r) => false);
                      }
                    },
                  )
                ],
              ),
            ),
          )
      ),
    );
  }
}

 

Student List

import 'package:flutter/material.dart';
import 'package:flutter_hive/screens/add_student.dart';
import 'package:flutter_hive/student.dart';
import 'package:hive/hive.dart';

class StudentListScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return StudentListScreenState();
  }
}

class StudentListScreenState extends State<StudentListScreen> {
  List<Student> listStudents = [];

  void getStudents() async {
    final box = await Hive.openBox<Student>('student');
    setState(() {
      listStudents = box.values.toList();
    });
  }

  @override
  void initState() {
    getStudents();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Flutter Hive Sample"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (_) => AddOrUpdateStudent(false,-1,null)));
              },
            )
          ],
        ),
        body: Container(
            padding: EdgeInsets.all(15),
            child: ListView.builder(
                itemCount: listStudents.length,
                itemBuilder: (context, position) {
                  Student getStudent = listStudents[position];
                  var email = getStudent.email;
                  var mobile = getStudent.mobile;
                  return Card(
                    elevation: 8,
                    child: Container(
                      padding: EdgeInsets.all(15),
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              children: [
                                Text("${getStudent.name} | Mobile: $mobile",
                                    style: TextStyle(fontSize: 18),maxLines: 2,overflow: TextOverflow.ellipsis,),
                                SizedBox(height: 8,),
                                Text("email : $email ",
                                    style: TextStyle(fontSize: 18))
                              ],
                            ),
                          ),
                         Row(
                           children: [
                             Container(

                               child: IconButton(
                                   icon: Icon(Icons.edit,color: Colors.blue,),
                                   onPressed: () {
                                     Navigator.push(
                                         context,
                                         MaterialPageRoute(
                                             builder: (_) => AddOrUpdateStudent(
                                                 true, position, getStudent)));
                                   }),
                             ),
                             IconButton(
                                 icon: Icon(Icons.delete,color: Colors.red,),
                                 onPressed: (){
                                   final box = Hive.box<Student>('student');
                                   box.deleteAt(position);
                                   setState(() => {
                                     listStudents.removeAt(position)
                                   });
                                 })
                           ],
                         )

                        ],
                      ),
                    ),
                  );
                })),
      ),
    );
  }
}

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

463 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions