Hive is a fast, secure No SQL database implementation for flutter applications. The hive database in Flutter uses the Dart package Hive for storing data locally and manipulating the data on a targeted device.
It stands out as being very fast in performing CRUD operations in comparison to SQLite and shared preference. Hive not only supports primitives, lists, and maps but also any Dart object you like. You need to generate a type adapter before you can store objects.
An offline To-Do App is a good example where you can use the hive database. Let’s check how we can implement hive in Flutter.
Read more about our Flutter app development services.
- Create a new project and add these dependencies:
1 2 3 4 5 6 7 8 |
dependencies: hive: ^2.2.3 hive_flutter: ^1.1.0 path_provider: ^2.1.1 dev_dependencies: hive_generator: ^2.0.1 build_runner: ^2.4.7 |
2. Hive can store data using dart primitive types, although, in production, we deal with model objects; to deal with objects, we need to generate TypeAdapter. ‘typeID’ is the identity of the object for the Hive to find it. HiveField must be annotated on the required field names, with their unique ID in the parameters.
1 2 3 4 5 6 7 8 9 10 11 |
import 'package:hive/hive.dart'; part 'Model.g.dart'; @HiveType(typeId : 0) class Person extends HiveObject{ @HiveField(0) String? name; Person(this.name); } |
3. Open the terminal and generate the file by entering the following: Flutter packages pub run build_runner build
4. After your .g file is generated, we have to register the adapter to be able to work with the generated Type Adapter.
1 2 3 4 5 6 7 8 |
hiveInit() async { Directory appDocDirectory = await getApplicationDocumentsDirectory(); var path = appDocDirectory.path; await Hive ..init(path) ..registerAdapter(PersonAdapter()); getData(); } |
CRUD OPERATIONS:
5. Open the HIve box: We need to open a data box so that we can add data to it.
1 |
Box box1 = await Hive.openBox('database'); |
6. Add data in the box.
1 2 3 4 5 |
addTask() async { Box box1 = await Hive.openBox('database'); Person person = Person(controller.text); box1.add(person.name); } |
7. Read the data you have added to the database.
1 2 3 4 5 6 |
getData() async { Box box1 = await Hive.openBox('database'); setState(() { names = box1.values.toList(); }); } |
8. You can also update data in the database by using the “putAt” function and providing data you want to add an index for where you want to add your data.
1 2 |
Box box1 = await Hive.openBox('database'); await box1.putAt(index,UpdateController.text); |
9. For deleting you need to call the delete function.
1 2 |
Box box1 = await Hive.openBox('database'); box1.deleteAt(index); |
That’s how we perform CRUD operations in Hive.
Demo app source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
void main() async { runApp(const MyApp()); WidgetsFlutterBinding.ensureInitialized(); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { TextEditingController controller = TextEditingController(); TextEditingController UpdateController = TextEditingController(); Person? person; List names = []; void initState() { super.initState(); hiveInit(); } hiveInit() async { Directory appDocDirectory = await getApplicationDocumentsDirectory(); var path = appDocDirectory.path; await Hive ..init(path) ..registerAdapter(PersonAdapter()); getData(); } getData() async { Box box1 = await Hive.openBox('database'); setState(() { names = box1.values.toList(); }); } addTask() async { Box box1 = await Hive.openBox('database'); Person person = Person(controller.text); box1.add(person.name); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Hive demo"), ), body: SingleChildScrollView( child: Column( children: [ Padding( padding: const EdgeInsets.all(20.0), child: TextField( controller: controller, decoration: const InputDecoration(border: OutlineInputBorder()), ), ), ElevatedButton( onPressed: () async { await addTask(); controller.clear(); }, child: Text("Add name")), ElevatedButton( onPressed: () { getData(); }, child: const Text("Read names")), ElevatedButton( onPressed: () async { Box box1 = await Hive.openBox('database'); await box1.clear(); getData(); }, child: const Text("Delete All")), Container( padding: const EdgeInsets.all(20.0), height: MediaQuery.of(context).size.width / 2, child: ListView.builder( itemCount: names.length, itemBuilder: (BuildContext context, int index) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ GestureDetector( onTap: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( content: const Text("Do you want to delete this?"), actions: [ Row( children: [ TextButton( onPressed: () { Navigator.pop(context); }, child: const Text("NO")), TextButton( onPressed: () async { Box box1 = await Hive.openBox( 'database'); box1.deleteAt(index); getData(); Navigator.pop(context); }, child: Text("YES")), ], ) ], ); }); }, child: SizedBox( height: 50, width: 200, child: Card( color: Colors.grey, elevation: 0.5, child: Padding( padding: const EdgeInsets.all(8.0), child: Text( names[index], style: const TextStyle(fontSize: 16), )), ), ), ), IconButton( onPressed: () async { showDialog( context: context, builder: (context) { return AlertDialog( actions: [ Column( children: [ TextField( controller: UpdateController, ), TextButton( onPressed: () async { Navigator.pop(context); Box box1 = await Hive.openBox( 'database'); await box1.putAt(index, UpdateController.text); getData(); }, child: const Text("Update Now")) ], ) ], ); }); }, icon: const Icon(Icons.edit)) ], ); }), ) ], ), ), ); } } |
Output :
Thanks for reading this article.
If I got something wrong, let me know in the comments. I would love to improve.
You can also read: https://mobikul.com/bottom-navigation-bar-in-flutter/