Hive Flutter Usage

1.5k views Asked by At

I am a newbee at Flutter and Hive, just learning. Here are some questions:

  1. I am using Value Listenable Builder, when I press the "Person age Up" person1 age is not updated, but if I press the setstate then is updated. How to auto update?

  2. Hive is a database; if I press the "Add person", it adds, and I see when I press "Print person lenght" but when reloaded the app person length is changed to 1 again, all adds removed:

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'departmentClass.dart';
import 'person.dart';

void main() async {
  await Hive.initFlutter('test');
  Hive.registerAdapter(DepartmentAdapter());
  Hive.registerAdapter(PersonAdapter());
  await Hive.openBox<Department>('testBox');

  runApp(MyApp());
}

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

class _MyAppState extends State<MyApp> {
  final Box testBox = Hive.box<Department>('testBox');

  @override
  Widget build(BuildContext context) {
    if (testBox.isEmpty) {
      final List<Person> personsAll = [];

      final person1 = new Person(23, "Maria");
      personsAll.add(person1);
      var mydepartment = new Department(34, "newD", personsAll);

      Hive.box<Department>('testBox').put("01", mydepartment);
    }
    return ValueListenableBuilder(
      valueListenable: testBox.listenable(),
      builder: (context, box, widget) {
        return MaterialApp(
          home: SafeArea(
            child: Scaffold(
              appBar: AppBar(
                title: Text("Hive Test"),
              ),
              body: Center(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("Hive  Sample"),
                  RaisedButton(
                    child: Text("Clear Box"),
                    onPressed: () {
                      Hive.box<Department>('testBox').clear();
                    },
                  ),
                  Text("Person1 Age Now: " + box.get("01").persons[0].age.toString()),
                  RaisedButton(
                    child: Text("Person age UP"),
                    onPressed: () {
                      box.get("01").persons[0].age++;
                      print(box.get("01").persons[0].age);
                    },
                  ),
                  RaisedButton(
                    child: Text("Set State"),
                    onPressed: () {
                      setState(() {});
                    },
                  ),
                  RaisedButton(
                    child: Text("Add person "),
                    onPressed: () {
                      final person2 = new Person(23, "Maria");
                      box.get("01").persons.add(person2);
                    },
                  ),
                  RaisedButton(
                    child: Text("Print person lenght "),
                    onPressed: () {
                      print("Persons: " + Hive.box<Department>('testBox').get("01").persons.length.toString());
                    },
                  )
                ],
              )),
            ),
          ),
        );
      },
    );
  }
}

2

There are 2 answers

0
Ali Bayram On BEST ANSWER

First of all when you open a box it is better to declare it's type in generic; final Box<Department> testBox = Hive.box<Department>('testBox');


Secondly if you want to notify the box that you're listening via ValueListenableBuilder, you need to put the value inside the box every time you changed the value;

box.get("01").persons[0].age++;

// this will notify the valuelistenablebuilder
box.put("01", box.get("01"));
print(box.get("01").persons[0].age);
0
lomza On

I have written an app where I used both Hive and cubits and it worked really well.

Below is AppDatabase class, where I have only one box ('book') and I open it up in the initialize() method, like below:

The whole application and tutorial is here.

const String _bookBox = 'book';

@Singleton()
class AppDatabase {
  AppDatabase._constructor();

  static final AppDatabase _instance = AppDatabase._constructor();

  factory AppDatabase() => _instance;

  late Box<BookDb> _booksBox;

  Future<void> initialize() async {
    await Hive.initFlutter();
    Hive.registerAdapter<BookDb>(BookDbAdapter());
    _booksBox = await Hive.openBox<BookDb>(_bookBox);
  }

  Future<void> saveBook(Book book) async {
    await _booksBox.put(
    book.id,
    BookDb(
      book.id,
      book.title,
      book.author,
      book.publicationDate,
      book.about,
      book.readAlready,
    ));
  }

  Future<void> deleteBook(int id) async {
    await _booksBox.delete(id);
  }

  Future<void> deleteAllBooks() async {
    await _booksBox.clear();
 }
}