import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDir = await getApplicationDocumentsDirectory();
Hive.init(appDocumentDir.path);
await Hive.openBox<String>('itemsBox');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SimpleHiveStorageScreen(),
);
}
}
class SimpleHiveStorageScreen extends StatefulWidget {
const SimpleHiveStorageScreen({super.key});
@override
State<SimpleHiveStorageScreen> createState() => _SimpleHiveStorageScreenState();
}
class _SimpleHiveStorageScreenState extends State<SimpleHiveStorageScreen> {
final TextEditingController _controller = TextEditingController();
late Box<String> itemsBox;
@override
void initState() {
super.initState();
itemsBox = Hive.box<String>('itemsBox');
}
void _addItem() {
final text = _controller.text.trim();
if (text.isNotEmpty) {
itemsBox.add(text);
_controller.clear();
}
}
void _deleteItem(int index) {
itemsBox.deleteAt(index);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Simple Hive Storage')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Enter new item'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _addItem,
child: const Text('Add Item'),
),
const SizedBox(height: 20),
const Text('Items:'),
Expanded(
child: ValueListenableBuilder(
valueListenable: itemsBox.listenable(),
builder: (context, Box<String> box, _) {
if (box.isEmpty) {
return const Center(child: Text('No items added yet'));
}
return ListView.builder(
itemCount: box.length,
itemBuilder: (context, index) {
final item = box.getAt(index);
return ListTile(
title: Text(item ?? ''),
onTap: () => _deleteItem(index),
);
},
);
},
),
),
],
),
),
);
}
}
This app uses Hive to store a list of strings locally on the device. We initialize Hive with the app documents directory and open a box named 'itemsBox' to hold our strings.
The UI has a TextField to enter new items and a button to add them. When the button is pressed, the text is trimmed and added to the Hive box, then the TextField is cleared.
The list of stored items is shown below using a ValueListenableBuilder that listens to changes in the Hive box. This automatically updates the UI when items are added or deleted.
Tapping an item deletes it from the box, which also updates the list instantly.
This simple example shows how Hive can be used for local NoSQL storage with reactive UI updates in Flutter.