In this tutorial we will build a simple todo app, which features data persistence all with Hive in under 100 lines of code!
First we create a new Flutter project:
flutter create todo_app
Inside the main() function, we initialize Hive and open up the box. We also call runApp() to allow Flutter to build our app.
Here’s the MyApp class that we call inside of runApp(). We have some undefined functions and variables but we’ll take care of those later.
The MyApp widget has a Scaffold which has a ValueListenableBuilder. That will rebuild the widget when our box changes.
Inside that builder is a ListView that holds all of the tasks in a ListTile.
Let’s add a FloatingActionButton inside of Scaffold with an onPressed callback which will return AlertDialog with TextField and TextButton.
Getting the Box
Before we can even do anything with the box, we have to get it. We already opened the box when we initialized Hive. The great thing about Hive is that you can get boxes anywhere, you don’t have to pass the box down from widget to widget. Just call Hive.box(). It’s a synchronous method so no messy async await stuff. It reads all of the values from the box and puts them in memory so we can access them.
Writing to the Box
Let’s create a method called onAddTask to save the task to the box. Here, we have used the add method instead of the put method, because it allows us to save the value with an auto-increment key.
Deleting from the Box
So, we added tasks to the box but how to delete them?
Let’s create a method called onDeleteTask to delete the task from the box. Here, we’re calling deleteAt method which deletes the n-th key from the box and the list will be rebuilt because we are listening to changes in the box using ValueListenableBuilder.
Congratulations, you have finished this tutorial where you have built a fully functional app that saves your todo. Feel free to change the UI to make it more beautiful than I did and add more features like the ability to filter out tasks you completed.
You can find the complete project on my GitHub:
In this tutorial we will build a simple todo app, which features data persistence all with Hive in under 100 lines of…
Do you want to learn more about Hive?
Let us know in the comments below.