Hive NoSql Database
For those who don’t know about NoSql?
NoSQL, which stands for “not only SQL,” which is an alternative of traditional relational databases in which data is placed in tables and data schema is carefully designed before the database is built. NoSQL databases are especially useful for working with large sets of distributed data.
What is Hive?
Hive is a lightweight, NoSQL database, easy to implement and also having high benchmark on the devices and written in the pure dart. Until and unless you need to model your data with many relationships, in that case it recommended to use SQLite.It has no native dependencies (it runs on Flutter Web!) can be the best option. Hive supports all platforms supported by Flutter.
Hive having the concept of boxes(which store data). A Box has to be opened before use. In addition to the plain-flavoured Boxes, there are also options which support lazy-loading of values and encryption.
What are Boxes?
All data stored in Hive is organized in boxes. A box can be compared to a table in SQL, but it does not have a structure and can contain anything. For a small app, a single box might be enough. For more advanced problems, boxes are a great way to organize your data. Boxes can also be encrypted to store sensitive data.
Before you can use a box, you have to open it. For regular boxes, this loads all of its data from the local storage into memory for immediate access.
var box = await Hive.openBox<E>('testBox');
To get an already opened instance, you can call Hive.box('testBox')
instead. It doesn’t matter though if you try to call openBox
multiple times. Hive is smart, and it will return an already opened box with the given name if you’ve previously called that method.
To prevent holding unnecessary data in memory, you can close the box when you are done with your box. Don’t worry if you forget to close the boxes . Smarty Hive do it for you. Its also has a handy method for closing all the box.
Hive supports all primitive types, List
, Map
, DateTime
, BigInt
and Uint8List
. Any object can be can stored using TypeAdapters.
In this, we are covering how to save a custom object(Employee)showing Basic CRUD operations:
Adding Dependencies:
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:
hive: latest version
hive_flutter: latest version
path_provider:
dev_dependencies:
flutter_test:
sdk: flutter
hive_generator:
build_runner:
Initializing and Registering Adapter:
Box _employeeBox;
@override
void initState() {
super.initState();
Hive.registerAdapter(EmployeeAdapter());
_openBox();
}
void _openBox() async{
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
_employeeBox = await Hive.openBox('employeeBox');
}
Under the hood, Hive works with binary data. It cannot recognise it
Box boxObject = await Hive.openBox('employee');
boxObject.add(Employee("paras" ,62));
its throws exception. or we save this by making it TypeAdapter.
import 'package:hive/hive.dart';
part 'employee.g.dart';
@HiveType(typeId: 1)
class Employee {
@HiveField(0)
final String name;
@HiveField(1)
final int id;
Employee(this.name, this.id);
}
And in Terminal type
:
flutter pub run build_runner build part ’employee.g.dart’
and you are done. This will generate you a TypeAdapter.
Save (Add)
We open the Box at the time of Initialization.
_employeeBox.add(Employee(employeeNameController.text, employeeHobbyController.text));
To show saved data in List (READ)
ListView.builder(shrinkWrap: true,
itemCount: _employeeBox.length,
itemBuilder: (context ,index)
{
final employee = _employeeBox.get(index) as Employee;
return Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text("${employee.name}",style: TextStyle(fontWeight: FontWeight.w400 ,fontSize: 15),), Text("${employee.hobby} ",style: TextStyle(fontWeight: FontWeight.w400 ,fontSize: 15),),
],
),
);
},)
For Updating and Deleting we use putAt() and deleteAt().
Link for repository:
https://github.com/parasarorahere/Hive-Database.git
Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.
Feel free to connect with us
And read more articles from FlutterDevs.com
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer 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 Facebook, GitHub, and Twitter for any flutter related queries.