Armazenamento Local com Hive e NoSQL
Aprenda a usar o Hive, um banco de dados NoSQL rápido de chave-valor para Flutter, para persistir objetos estruturados localmente sem SQL.
Armazenamento Local com Hive e NoSQL é uma aula grátis de Flutter Mobile Development no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Flutter Mobile Development, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Flutter Mobile Development inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Hive?
Hive is a lightweight, pure-Dart key-value database. It is great when SQLite feels heavy and SharedPreferences feels too simple.
- Very fast reads and writes
- No native dependencies
- Stores Dart objects directly
Adding Hive
Add the packages to pubspec.yaml: hive, hive_flutter, and dev dependencies hive_generator and build_runner.
dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
dev_dependencies:
hive_generator: ^2.0.1
build_runner: ^2.4.0Initializing Hive
Initialize Hive before runApp so the database directory is ready.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
runApp(const MyApp());
}Boxes
Data lives in a Box — think of it as a typed map persisted to disk. Open one before use.
final box = await Hive.openBox('settings');Reading & Writing
Use put and get like a map. Values survive app restarts.
box.put('darkMode', true);
final isDark = box.get('darkMode', defaultValue: false);Storing Custom Objects
To store your own classes, annotate them with @HiveType and each field with @HiveField.
@HiveType(typeId: 0)
class Note extends HiveObject {
@HiveField(0)
String title;
@HiveField(1)
String body;
Note(this.title, this.body);
}Generating Adapters
Run the code generator to create the type adapter, then register it.
// terminal:
// flutter pub run build_runner build
Hive.registerAdapter(NoteAdapter());Working with a Typed Box
Open a box typed to your class to store and retrieve objects directly.
final notes = await Hive.openBox<Note>('notes');
notes.add(Note('Shopping', 'Milk and eggs'));
final first = notes.getAt(0);Updating & Deleting
Because a HiveObject remembers its box, you can call save and delete on the object itself.
final note = notes.getAt(0)!;
note.title = 'Updated';
note.save();
note.delete();Reactive UI with ValueListenable
Hive boxes expose a listenable, so ValueListenableBuilder rebuilds the UI when data changes.
ValueListenableBuilder(
valueListenable: notes.listenable(),
builder: (context, Box<Note> box, _) {
return Text('Notes: ' + box.length.toString());
},
);Hive vs SQLite
Choose Hive for simple object/key-value storage and speed. Choose SQLite when you need complex relational queries, joins or aggregations.
Quick Check
What must you do before storing a custom class in a Hive box?
Recap
You learned Hive for local NoSQL storage:
- initFlutter and boxes
- put/get key-value access
- Custom objects with generated adapters
- Reactive UI via box listenables
Hive gives you fast, structured persistence without SQL.
Perguntas Frequentes
A aula “Armazenamento Local com Hive e NoSQL” é grátis?
Sim — o texto completo de “Armazenamento Local com Hive e NoSQL” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Flutter Mobile Development, atualize para CoddyKit PRO. O curso de Flutter Mobile Development inclui 4 aulas no total.
O que vou aprender em “Armazenamento Local com Hive e NoSQL”?
Aprenda a usar o Hive, um banco de dados NoSQL rápido de chave-valor para Flutter, para persistir objetos estruturados localmente sem SQL. Você pratica Flutter Mobile Development com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Flutter Mobile Development?
Nenhuma experiência prévia é necessária. Flutter Mobile Development no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Armazenamento Local com Hive e NoSQL”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Flutter Mobile Development?
Sim. Cada aula de Flutter Mobile Development inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Preferências compartilhadas para dados
- Integração de banco de dados SQLite
- Operações no sistema de arquivos
- Armazenamento Local com Hive e NoSQL