Hive DataBase With TypeAdapter In Flutter

Learn How To Create Todo Application Using Hive DataBase With TypeAdapter In Your Flutter Apps

Shaiq khan
Jan 6 · 9 min read
Image for post
Image for post
Hive DataBase With TypeAdapter In Flutter

Many applications require information handling on the phone and, further, their synchronization with the backend. For instance, to-do lists, arrangements of any information (analyzes, notes, and so forth). It’s not under any condition cool when the list of only a couple thousand things while erasing one of them and afterward keeping in touch with the cache or looking through the cache begins to back off.

Quite possibly, the main part of application development is data storage and manipulation, and the equivalent is valid for flutter applications. There are numerous approaches to store local data in flutter applications.

In this post, we will explore the Hive DataBase With TypeAdapter In Flutter. We will also implement a demo program, create a todo app using packages, and use them in your flutter applications.

Table Of Contents::

Hive

Hive Boxes

Type Adapters

Why Hive DataBase

Advantages

Implementation

Code Implement

Code File

Conclusion

Hive:

Hive is a quick, lightweight, NoSQL database for flutter and dart applications. Hive is truly helpful if you need a straightforward key-value database, without numerous relations, and truly simple to utilize. It is an offline database(store data in local devices). It has no native dependencies (it runs on Flutter Web!) can be the ideal choice. Hive bolsters all stages upheld by Flutter.

Hive having the idea of boxes(which store data). A Box must be opened before use. Notwithstanding the plain-enhanced Boxes, there are additional alternatives that help lazy-loading of values and encryption.

Demo Module ::

Image for post
Image for post
Demo Module

In this screenshot of the demo, there was a to-do list, and all red color tick will show progress, and the purple tick will show completed, and we also used filter the data using Hive in your flutter applications.

Hive Boxes:

Hive stores its data in boxes containing key-value sets. I like to see boxes as an organizer with files listed and arranged by a numbering framework or as normal maps in the dart. With hive, before you can read/compose data, a box should be opened. Boxes can be opened with await Hive.Openbox(‘name’) can get an instance of an opened box with Hive. Box (‘name’), where ‘name’ is the name of the case (saying the DB name).

You can call Hive.openBox(‘name’) regardless of whether you as of now have the box opened elsewhere, here and there it very well might be smart to do this.

Type Adapters:

Hive permits you to store most standard types — String, int, Map, List, DateTime, yet you need to have a model class for your data since this makes development a lot simpler and quicker. To utilize these model kinds, you need to enroll TypeAdapters, which causes you to encode/decode your item to binary form on a disk.

You can manually compose your Type Adapters, yet we’ll generate our own with the hive_generator and build_runner packages we added to our dev dependencies earlier. Somewhere in your lib/folder, you can make your model file.

Why Hive DataBase?:

  • It’s the most efficient database in terms of speed and performance compared to SQFlite and SharedPrefrences.
  • It provides a straightforward way to perform basic (CRUD) operations.

Advantages:

  • Cross-platform: since there are no native dependencies on pure Dart — mobile, desktop, browser.
  • High performance.
  • Built-in strong encryption.
  • NO native dependencies.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

hive: ^1.4.1+1
hive_flutter: ^0.3.0+2
path_provider: ^1.6.5

Step 2: Add the dev dependencies

Add dev dependencies to pubspec — yaml file.

dev_dependencies:

hive_generator: ^0.7.0+2
build_runner: ^1.8.0

Step 3: Import

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';

Step 4: Run flutter packages get in the root directory of your app.

Step 5: Enable AndriodX

Add this to your grade.properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file :

You need to implement it in your code respectively:

Now let’s create the class and add the right annotations so the TypeAdapters can be generated:

Let’s build a model class, e.g., DataModel.

import 'package:hive/hive.dart';

part 'data_model.g.dart';

@HiveType(typeId: 0)
class DataModel{
@HiveField(0)
final String title;
@HiveField(1)
final String description;
@HiveField(2)
final bool complete;

DataModel({this.title, this.description, this.complete});

}

First import hive. At that point, add ‘data_model.g.dart’ as a section (this is where the type adapter is generated). Clarify the model class with @HiveType(), so the generator realizes this should be a TypeAdapter. Annotate on each field you need to save with @HiveField(index), the index is an int, and each index ought to show up once, and you shouldn’t transform it in the wake of enlisting them. We have three factors like title, description, and complete to store, and they are explained as @HiveField.

Now, We will run a code generator by typing the following command in the terminal which will automatically generate database code for us.

$ flutter packages pub run build_runner build

Note: File name is `data_model.dart`. We will add a line part ‘data_model.g.dart’.Where g stands for generated. Thus new generated file would be data_model.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'data_model.dart';

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

class DataModelAdapter extends TypeAdapter<DataModel> {
@override
final typeId = 0;

@override
DataModel read(BinaryReader reader) {
var numOfFields = reader.readByte();
var fields = <int, dynamic>{
for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return DataModel(
title: fields[0] as String,
description: fields[1] as String,
complete: fields[2] as bool,
);
}

@override
void write(BinaryWriter writer, DataModel obj) {
writer
..writeByte(3)
..writeByte(0)
..write(obj.title)Demo
..writeByte(1)
..write(obj.description)
..writeByte(2)
..write(obj.complete);
}
}

Create a new dart file called my_home_page.dart inside the lib folder.

floatingActionButton: FloatingActionButton(
onPressed: (){
showDialog(
context: context,
child: Dialog(

backgroundColor: Colors.blueGrey[100],
child: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: "Title"),
controller: titleController,
),
SizedBox(
height: 8,
),
TextField(
decoration: InputDecoration(
hintText: "Description"),
controller: descriptionController,
),
SizedBox(
height: 8,
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.red,
child: Text("Add Data",style: TextStyle(color: Colors.white),),
onPressed: () {
final String title = titleController.text;
final String description = descriptionController.text;
titleController.clear();
descriptionController.clear();
DataModel data = DataModel(title: title, description: description, complete: false);
dataBox.add(data);
Navigator.pop(context);

},
)
],
),
)
)
);
},
child: Icon(Icons.add),
),

On this screen, we will make a FloatingActionButton(). In this button onPressed()method, we will open a dialog box with text fields.

Image for post
Image for post
Dialog Box With Text Fields

When we tap on the floating button, then a dialog box will open with a text field, and then we will write any title, description and then press on add data button, then data will show on your screen.

ValueListenableBuilder(
valueListenable: dataBox.listenable(),

builder: (context, Box<DataModel> items, _){

List<int> keys= items.keys.cast<int>().toList();
return ListView.separated(
separatorBuilder: (_, index) => Divider(),
itemCount: keys.length,
shrinkWrap: true,
scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(),
itemBuilder:(_, index){
final int key = keys[index];
final DataModel data = items.get(key);
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
color: Colors.blueGrey[200],
child: ListTile(
title: Text(data.title, style: TextStyle(fontSize: 22,color: Colors.black),),
subtitle: Text(data.description,style: TextStyle(fontSize: 20,color:Colors.black38)),
leading: Text("$key", style: TextStyle(fontSize: 18,color: Colors.black),),

),
);
},

);
},
),

We will use ValueListenableBuilder(), In this builder ,we will return a ListView.separated(). We will add a separator builder, itemCount, shrinkWrap, and itemBuilder. In itemBuilder, we will return a Card.

Image for post
Image for post
Data

On this screen, We will add a card and add a ListTile(). Add title, description, index. We will add a trailing on a list tile method when we add the tick icon on the right side.

trailing: Icon(Icons.check, color: data.complete ? Colors.deepPurpleAccent : Colors.red,),

When data are completed, the color was purple otherwise was red. Now we will create a tap function on the list tile method and open a dialog box.

onTap: (){
showDialog(
context: context,
child: Dialog(
backgroundColor: Colors.white,
child: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.blueAccent[100],
child: Text("Mark as complete",
style: TextStyle(color: Colors.black87),
),
onPressed: () {
DataModel mData = DataModel(
title: data.title,
description: data.description,
complete: true
);
dataBox.put(key, mData);
Navigator.pop(context);
},
)
],
),
)
)
);
},

In this dialog box, we will make a button; on this button, a text will be shown “Mark as complete.” When we click on this button, the tick color was changed from red to purple or from progress to complete.

Image for post
Image for post
Completed Data

Now we will add a filter, and we will make three types of the filter; the first was All. In this method, all the data will be shown all your screen. The second was Completed, In this method, only completed data will be shown, and last was Progress, In this method, only progress data will be shown, and the tick color was red.

enum DataFilter {ALL, COMPLETED, PROGRESS}

We will make a PopupMenuButton(). In this button, we will add All, Completed, and Progress with DataFilter. The menu is shown on the right side of the app bar.

PopupMenuButton<String>(
onSelected: (value) {
if(value.compareTo("All") == 0){
setState(() {
filter = DataFilter.ALL;
});
}else if (value.compareTo("Compeleted") == 0){
setState(() {
filter = DataFilter.COMPLETED;
});
}else{
setState(() {
filter = DataFilter.PROGRESS;
});
}
},
itemBuilder: (BuildContext context) {
return ["All", "Compeleted", "Progress"].map((option) {
return PopupMenuItem(
value: option,
child: Text(option),
);
}).toList();
},
)

When we click on any filter type, they will show only those items data but initially, data default show “All.”

Image for post
Image for post
Filter

We will add a filter function on ValueListenableBuilder() and map to the keys with DataFilter.

if(filter == DataFilter.ALL){
keys = items.keys.cast<int>().toList();
}else if(filter == DataFilter.COMPLETED){
keys = items.keys.cast<int>().where((key) => items.get(key).complete).toList();
}else{
keys = items.keys.cast<int>().where((key) => !items.get(key).complete).toList();
}

When we run the application, we ought to get the screen’s output like the underneath video capture.

Image for post
Image for post
Final Output

In this Final video output, you will see how Hive DataBase With TypeAdapter will work and how to use filters to change data in your flutter applications.

Code File:

Conclusion:

In the article, I have explained the basic structure of the Hive DataBase. With TypeAdapter in a flutter, you can modify this code according to your choice. This was a small introduction to Hive DataBase With TypeAdapter Using Hive On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information in Trying up to Hive DataBase With TypeAdapter in your flutter projects. We will show you the hive is?, TypeAdapter is?, and working on a hive database with a type adapter using hive in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

find the source code of the Flutter Hive Database Demo:

Feel free to connect with us:
And read more articles from .

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on , , , and for any flutter related queries.

We and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Image for post
Image for post

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high…

Shaiq khan

Written by

Flutter Developer

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Shaiq khan

Written by

Flutter Developer

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store