Introduction
Hive is a simple way to save and get data on your device without using complex databases. It helps apps remember things even after closing.
Hive is a simple way to save and get data on your device without using complex databases. It helps apps remember things even after closing.
var box = await Hive.openBox('boxName'); // To save data await box.put('key', value); // To read data var value = box.get('key');
openBox to create or open a storage container called a box.put to save data with a key, and get to read it back.var box = await Hive.openBox('settings'); await box.put('darkMode', true); bool darkMode = box.get('darkMode');
var box = await Hive.openBox('favorites'); await box.put('song1', 'Imagine'); String song = box.get('song1');
This program opens a box called 'myBox', saves the name 'Alice', then reads and prints it.
import 'package:hive/hive.dart'; void main() async { var box = await Hive.openBox('myBox'); // Save data await box.put('name', 'Alice'); // Read data var name = box.get('name'); print(name); }
Hive stores data locally on the device, so it works offline.
Data is saved as key-value pairs, like a dictionary.
Remember to await async calls like openBox and put to avoid errors.
Hive is an easy local storage for Flutter apps.
Use boxes to save and get data with keys.
Great for small data like settings or favorites.
settings?await Hive.openBox('boxName').var box = await Hive.openBox('settings'); uses await and openBox correctly. Omitting await on Hive.openBox('settings') returns a Future. Hive.box('settings') only accesses an already opened box synchronously, and awaiting Hive.box('settings') is incorrect as it is synchronous.var box = await Hive.openBox('favorites');
await box.put('color', 'blue');
print(box.get('color'));put method saves a value with a key, here 'color' = 'blue'. The get method retrieves the value for the key.box.get('color') returns 'blue', which is printed.var box = Hive.openBox('settings');
await box.put('theme', 'dark');favorites. Which code correctly saves and retrieves this list?await box.put(key, value) with key as string and value as list to save data.box.get(key) synchronously to get saved list. Await is not needed for get.Pass the test and this pattern moves unknown