Basic Hive Setup In A Flutter App

Implementing Hive In A Flutter To-Do List App

In this tutorial, we’ll explore how to create a Basic Hive setup in a Flutter App, a lightweight and fast NoSQL database, into a Flutter to-do list application. Hive is a great choice for local data persistence in Flutter due to its simplicity and performance.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Flutter and how to set up a new Flutter project. You also need to have the Flutter SDK and an editor like Visual Studio Code or Android Studio installed on your machine.

Getting Started

Let’s start by creating a new Flutter project. Open your terminal or command prompt and run the following command:

flutter create hive_todo_app

This command will create a new Flutter project called hive_todo_app.

Next, navigate to the project directory:

cd hive_todo_app

Adding Dependencies

Open the pubspec.yaml file in your project and add the following dependencies under the dependencies section:

https://pub.dev/packages/hive

https://pub.dev/packages/hive_flutter

dependencies:  
flutter:    
sdk: flutter  
hive: ^2.0.4 
hive_flutter: ^1.0.0

The hive package is the core package for Hive, while hive_flutter provides additional functionality specifically for Flutter.

Save the file and run the following command to fetch the dependencies:

flutter pub get

Initializing Hive

Now that we have added the necessary dependencies, we can initialize Hive in our app.

Create a new file called main.dart in the lib folder of your project. Replace the contents of this file with the following code:

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

void main() async {  
  await Hive.initFlutter();  
  await Hive.openBox('todoBox');  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {    
   return MaterialApp(
      title: 'Todo App',      
      theme: ThemeData(        
               primarySwatch: Colors.blue,        
               visualDensity: VisualDensity.adaptivePlatformDensity,
             ),
      home: TodoListScreen(),    
  );  
 }
}

In the main function, we first call Hive.initFlutter() to initialize Hive with Flutter. Then, we open a Hive box called 'todoBox' using Hive.openBox('todoBox'). This box will be used to store our to-do items.

The MyApp widget is a simple MaterialApp that serves as the entry point of our app. We set the app’s title and theme and specify that the TodoListScreen should be the home screen.

Creating The To-Do List Screen

Let’s create the screen that will display the list of to-do items.

Create a new file called todo_list_screen.dart in the lib folder. Replace the contents of this file with the following code:

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

class TodoListScreen extends StatefulWidget {  
@override  _TodoListScreenState createState() => _TodoListScreenState();}

class _TodoListScreenState extends State<TodoListScreen> {  
late Box<Todo> _todoBox;  

@override  
void initState() {   
 super.initState();   
 _todoBox = Hive.box('todoBox');  
}  

@override  
Widget build(BuildContext context) {    
return Scaffold(      
appBar: AppBar(title: Text('Todo List'),
),
body: ValueListenableBuilder<Box<Todo>>(
  valueListenable: _todoBox.listenable(),       
  builder: (context, box, _) {          
    return ListView.builder(            
      itemCount: box.length,            
      itemBuilder: (context, index) {
        final todo = box.getAt(index)!;              
        return ListTile( 
                 title: Text(todo.title),  
                 subtitle: Text(todo.description),    
          );        
    },       
   );      
  },    
  ),      
floatingActionButton: FloatingActionButton(
  child: Icon(Icons.add),   
  onPressed: () {   
    showDialog(          
      context: context,          
      builder: (context) { 
        String title = '';   
        String description = '';     
        return AlertDialog(   
          title: Text('Add Todo'),     
          content: Column(  
            mainAxisSize: MainAxisSize.min,  
            children: [      
              TextField( 
                onChanged: (value) { 
                  title = value; 
                },      
                decoration: InputDecoration( 
                  labelText: 'Title',
                ),        
              ),           
              TextField(      
                onChanged: (value) {  
                  description = value;  
                 },    
                decoration: InputDecoration(  
                  labelText: 'Description', 
                ),     
               ),    
              ],     
           ),    
            actions: [   
               FlatButton(  
                 child: Text('Cancel'),
                 onPressed: () {    
                    Navigator.of(context).pop(); 
                   }, 
                 ),   
               FlatButton(  
                  child: Text('Save'), 
                   onPressed: () { 
                     final todo = Todo( 
                       title: title, 
                       description: description, 
                     );    
                     _todoBox.add(todo); 
                     Navigator.of(context).pop();  
                  },     
             ),      
          ],       
       );       
     },      
    );     
   },    
  ),  
  );  
 }
}

The TodoListScreen class extends StatefulWidget and is responsible for displaying the list of to-do items and providing an interface for adding new items.

In the initState method, we initialize the _todoBox variable with the Hive.box('todoBox') box. This gives us access to our to-do items stored in Hive.

The build method returns a Scaffold widget that has an AppBar with the title “Todo List” and a body with a ValueListenableBuilder. The ValueListenableBuilder listens for changes in the todoBox and rebuilds the UI whenever a change occurs. Inside the builder function, we create a ListView.builder that displays the to-do items as a list of ListTile widgets.

The floatingActionButton is used to open a dialog when pressed. The dialog contains two TextField widgets for entering the title and description of a new to-do item. When the “Save” button is pressed, we create a new Todo object with the entered values, add it to the _todoBox, and close the dialog.

Creating The Todo Model

We need to define a Todo model class that represents a single to-do item. Create a new file called todo_model.dart in the lib folder. Replace the contents of this file with the following code:

import 'package:hive/hive.dart';
part 'todo_model.g.dart';

@HiveType(typeId: 0)
class Todo extends HiveObject {  
@HiveField(0)  
String title;  
@HiveField(1)  
String description;  

Todo({required this.title,required this.description,});}

In this class, we annotate our Todo class with a @HiveType annotation. This annotation tells Hive that this class should be used for storing and retrieving to-do items.

The @HiveField annotation is used for specifying the indices of fields in the Hive database. In our case, we have two fields: title and description.

To generate the necessary Hive code, run the following command in your terminal:

flutter packages pub run build_runner build

Running The App

Now that everything is set up, let’s run our app and see the results.

Connect your device or start an emulator, and run the following command in your terminal:

flutter run

This command will build and run the Flutter project on your connected device or emulator.

Once the app is launched, you should see a screen with the title “Todo List” and an empty list. Tap on the floating action button to add a new to-do item. Enter a title and description, then tap “Save”. Your new to-do item should appear in the list.

Congratulations! You have successfully implemented Hive in a Flutter to-do list app. Hive provides a simple and efficient way to persist data locally in your Flutter applications. Explore the Hive documentation to learn more about its powerful features and improve your app further.

Conclusion

In this tutorial, we learned how to integrate Hive into a Flutter to-do list application. We covered initializing Hive, creating a Hive box, rendering data using ValueListenableBuilder, and adding new data to the Hive box. With this knowledge, you can now implement Hive in your own apps to persist data locally and create powerful offline experiences for your users. Happy coding!

View the full code on our Github Repository here.

iDigiSol Web offers app development and E-commerce consulting services. Contact us TODAY!