Photo by Alexas_Fotos from Pixabay.com

Connecting Hive (database) with Provider (state management)

Madebysharing
Flutter Community

--

In this Todo-List app example we will be connecting Hive (a fast, secure, NoSQL Database) with Provider (a Flutter favorite for state management). We’ll be storing a todo list in the database as a string list and our app color theme as a string. This app uses the Model View Controller (MVC) design pattern.

https://github.com/madebysharing/flutter_hive_provider_example

To give us the option to access our database at start up, we will open our Hive database box in main() by changing main() to be asynchronous and then passing our database box to our Controllers. In this case; ThemeController and TodoListController, which are using Provider for state management. Using Multiprovider in our app allows us to load more than one provider, allowing us to better organize our code.

Looking inside our TodoListController class, we instantiate our database in the constructor and now we can do all our database manipulation from within our controller!

Other details to notice is that our class extends ‘ChangeNotifier’, which allows our Controller to notify other widgets in our app of state changes to our Model by using notifyListeners().

An example benefit of loading our database at startup is the ability to load a theme the user may have chosen. Looking at our routes.dart file, we load our Controller inside didChangeDependencies(), which gives us access to our Controller before the widget starts building, allowing us to set a theme.

And that’s it! Enjoy!

Rick and Morty

--

--