Hive Local Database In Flutter

Hive Local Database In Flutter :

Screenshot :

Hive Local Database In Flutter

Model Package :

contact.dart

import 'package:hive/hive.dart';

part 'contact.g.dart';

@HiveType()
class Contact {
  @HiveField(0)
  final String name;
  @HiveField(1)
  final int age;

  Contact(this.name, this.age);
}

contact.g.dart

part of 'contact.dart';

class ContactAdapter extends TypeAdapter<Contact> {
  @override
  Contact read(BinaryReader reader) {
    var numOfFields = reader.readByte();
    var fields = <int, dynamic>{
      for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Contact(
      fields[0] as String,
      fields[1] as int,
    );
  }

  @override
  void write(BinaryWriter writer, Contact obj) {
    writer
      ..writeByte(2)
      ..writeByte(0)
      ..write(obj.name)
      ..writeByte(1)
      ..write(obj.age);
  }
}

contact_page.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'models/contact.dart';
import 'new_contact_form.dart';

class ContactPage extends StatelessWidget {
  const ContactPage({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Hive Tutorial'),
        ),
        body: Column(children: <Widget>[
          Expanded(child: _buildListView()),
          NewContactForm(),
        ]));
  }

  Widget _buildListView() {
    return WatchBoxBuilder(
        box: Hive.box('contacts'),
        builder: (context, contactsBox) {
          return ListView.builder(
              itemCount: contactsBox.length,
              itemBuilder: (context, index) {
                final contact = contactsBox.getAt(index) as Contact;

                return ListTile(
                    title: Text(contact.name),
                    subtitle: Text(contact.age.toString()),
                    trailing:
                        Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                      IconButton(
                          icon: Icon(Icons.refresh),
                          onPressed: () {
                            contactsBox.putAt(
                              index,
                              Contact('${contact.name}*', contact.age + 1),
                            );
                          }),
                      IconButton(
                          icon: Icon(Icons.delete),
                          onPressed: () {
                            contactsBox.deleteAt(index);
                          })
                    ]));
              });
        });
  }
}

new_contact_form.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'models/contact.dart';

class NewContactForm extends StatefulWidget {
  @override
  _NewContactFormState createState() => _NewContactFormState();
}

class _NewContactFormState extends State<NewContactForm> {
  final _formKey = GlobalKey<FormState>();

  String _name;
  String _age;

  void addContact(Contact contact) {
    final contactsBox = Hive.box('contacts');
    contactsBox.add(contact);
  }

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child: Column(children: <Widget>[
          Row(children: <Widget>[
            Expanded(
                child: TextFormField(
              decoration: InputDecoration(labelText: 'Name'),
              onSaved: (value) => _name = value,
            )),
            SizedBox(width: 10),
            Expanded(
                child: TextFormField(
              decoration: InputDecoration(labelText: 'Age'),
              keyboardType: TextInputType.number,
              onSaved: (value) => _age = value,
            ))
          ]),
          RaisedButton(
              child: Text('Add New Contact'),
              onPressed: () {
                _formKey.currentState.save();
                final newContact = Contact(_name, int.parse(_age));
                addContact(newContact);
              })
        ]));
  }
}

pubspec.yaml

name: hive_db_local
description: A new Flutter application.
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  hive:
  hive_flutter:
  path_provider:
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  hive_generator:
  build_runner:

flutter:
  uses-material-design: true

main.dart

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'contact_page.dart';
import 'models/contact.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDirectory =
      await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  Hive.registerAdapter(ContactAdapter(), 0);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Hive Tutorial',
        home: FutureBuilder(
            future: Hive.openBox('contacts',
                compactionStrategy: (int total, int deleted) {
              return deleted > 20;
            }),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError)
                  return Text(snapshot.error.toString());
                else
                  return ContactPage();
              } else
                return Scaffold();
            }));
  }

  @override
  void dispose() {
    Hive.box('contacts').compact();
    Hive.close();
    super.dispose();
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in