Favourite List
Nothing Added.

Flutter Hive NoSQL Database Easy Explanation With Sample Project

Flutter Hive


Flutter Hive is a package of lightweight and fast key-value pair NoSQL database that stores data locally to be accessed easily in flutter application. The idea behind this Database comes from a request given by Google on an open source contribution request. The Hive team has written an implementation of the proposed API and have it released as an open source package that can be used in your Flutter application. 

In this article , we are implementing Hive NoSQL database in our Flutter project and do some CRUD operation with easy explanation. Let's learn some basic about database. If you know about SQL and NoSQL, you can skip this section.

Difference Between SQL and NoSQL Database

When comparing databases, you will often hear the terms “NoSQL” and “SQL” thrown around interchangeably. But these are not the same thing. There are many differences between SQL and NoSQL, so let’s look at a few of them here.

SQL

SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database.
These databases have fixed or static or predefined schema. These databases are best suited for complex queries.
Examples: PostgreSQL, MySQL, Oracle, MS-SQL Server etc

NoSQL

The NoSQL is the non-relational database management system in which it does not have a stable schema, it is simple to laminate, and it does not use relation with each other, this database has been used for dispersed data storing and it can be used for huge data and it works as real-time database. That means it fast then SQL.

Examples: MongoDB, GraphQL, HBase, Neo4j, Cassandra etc

In this article we are implementing hive NOSQL database on our project. So create a flutter project and let's start.

Flutter  Hive Dependency

We are using hive and path provider to make it work. For that , add this line of code to your pubspec.yaml dependency, and pub get.

  hive: ^2.2.2
  hive_flutter: ^1.1.0
  path_provider: ^2.0.11


Initialize Hive and Create a Collection Box 

First of all, we have to initialize our hive database into our root widget. For that, add this line on main.dart file.


Future<void> main() async {
  //Initisilize hive 
  WidgetsFlutterBinding.ensureInitialized();
  Directory directory = await getApplicationDocumentsDirectory();
  Hive.init(directory.path);

  //Working with hive needs to open box, hive is like boxes with key value.
  //It's work like firebase collection
  await Hive.openBox('DemoBox');
  runApp(const MyApp());
}

Hive CRUD Functions

CRUD means Create, Read, Update, Delete. Here are CRUD function for Hive database. Don't worry I will give full source code. This is just explanation, You have to add them into a statefull widget.

 //Access to the Open Box/collection
  Box DemoBox = Hive.box('DemoBox');
  //Create a key
  String? name = 'This Value Will Change';

//function for adding to the box
  addFriend() async {
    await DemoBox.put('name', 'Flutter Hive');
    
  }

//read from the box
  readFriend() async {
    //put it on setstate to get the update value
    setState(() {
      name = DemoBox.get('name');
     
    });
  }

//update box value
  updateFriend() async {
    await DemoBox.put('name', 'Text Updated');
  }

//delete from the box
  deleteFriend() async {
    await DemoBox.delete('name');
  }


Hive Full Project Source Code

Here is the Full Project Source Code. Copy and replace with main.dart file. 

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hivedb/home.dart';
import 'package:path_provider/path_provider.dart';

Future<void> main() async {
  //Initisilize hive 
  WidgetsFlutterBinding.ensureInitialized();
  Directory directory = await getApplicationDocumentsDirectory();
  Hive.init(directory.path);

  //Working with hive needs to open box, hive is like boxes with key value.
  //It's work like firebase collection
  await Hive.openBox('DemoBox');
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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





class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //Access to the Open Box/collection
  Box DemoBox = Hive.box('DemoBox');
  //Create a key
  String? name = 'This Value Will Change';

//function for adding to the box
  addFriend() async {
    await DemoBox.put('name', 'Flutter Hive');
    
  }

//read from the box
  readFriend() async {
    //put it on setstate to get the update value
    setState(() {
      name = DemoBox.get('name');
     
    });
  }

//update box value
  updateFriend() async {
    await DemoBox.put('name', 'Text Updated');
  }

//delete from the box
  deleteFriend() async {
    await DemoBox.delete('name');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hive DB'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '§name',
              style: TextStyle(fontSize: 32),
            ),
          
            SizedBox(
              height: 20,
            ),
            ElevatedButton(onPressed: addFriend, child: Text('Create')),
            ElevatedButton(onPressed: readFriend, child: Text('Read')),
            ElevatedButton(onPressed: updateFriend, child: Text('Update')),
            ElevatedButton(onPressed: deleteFriend, child: Text('Delete'))
          ],
        ),
      ),
    );
  }
}


FAQ:

Is there a NoSQL database for flutter?

There are two package for database handling on Flutter. Sqflite and Hive. SQflite is for SQL database and Hive for NonSQL Database.

What is the best alternative to SQLite for flutter?

The best alternative for SQLite is Hive. Hive is fast lightweight and fast key-value pair NoSQL database.

 
Next Post Previous Post
Feels like
No Comment
Add Comment
comment url