Gestion de données locales avec Hive dans Flutter
Gestion de données locales avec Hive dans Flutter
-
Objectif
- Apprendre à utiliser Hive, une base de données locale rapide et légère, pour stocker et gérer des notes/tâches dans une application Flutter.
-
Créer un projet Flutter
-
🚀 Étape 1 : Créer un projet Flutter
- Créer un projet avec
flutter create hive_app
. - Se déplacer dans le projet :
cd hive_app
. -
📦 Étape 2 : Ajouter les dépendances
- Dans
pubspec.dart
, ajoutez les dépendances suivantes pour Hive et path_provider : - Exécutez
flutter pub get
pour installer les dépendances : -
Fichier d’Application Principal
-
⚙️ Étape 3 : Initialiser Hive dans main
- Dans
main.dart
, configurez la structure de base de l’application Flutter et initialisez Hive: -
Créer les pages
-
🏠 Étape 4 : Créer la page d’accueil
- Fichier
home_page.dart
→ interface pour ajouter, afficher et gérer les tâches. - Utilisation de
ValueListenableBuilder
pour réactivité. - Ajout / suppression par
ListTile
. -
📝 Étape 5 : Boîte de dialogue
- Utiliser
AlertDialog
pour saisir une tâche. - Exemple d’ajout :
-
🛠️ Bonnes pratiques
- Toujours ouvrir les
boxes
avant utilisation. - Utiliser
ValueListenableBuilder
pour une UI réactive. - Éviter de stocker des objets trop complexes → préférer SQLite/Drift.
- Bien choisir les
typeId
uniques pour les adapters. -
📊 Hive vs SQLite vs Drift
-
👉 Conclusion
- Utiliser Hive pour une persistance rapide et simple (favoris, cache, settings).
- Préférer SQLite ou Drift pour des données relationnelles complexes.
dependencies:
flutter:
sdk: flutter
hive: ^2.2.3
hive_flutter: ^1.1.0
path_provider: ^2.1.1
dev_dependencies:
hive_generator: ^1.1.0
build_runner: ^2.4.0
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'pages/home_page.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialiser Hive
await Hive.initFlutter();
// Ouvrir la boîte (box) Hive
await Hive.openBox('todos_box');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Application Hive',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.red),
useMaterial3: true,
),
home: const HomePage(),
);
}
}
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State createState() => _HomePageState();
}
class _HomePageState extends State {
final TextEditingController _textEditingController = TextEditingController();
late Box _todosBox;
@override
void initState() {
super.initState();
_todosBox = Hive.box('todos_box');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Notes !",
style: TextStyle(
color: Colors.white,
),
),
backgroundColor: Colors.red,
),
body: _buildUI(),
floatingActionButton: FloatingActionButton(
onPressed: () => _displayTextInputDialog(context),
backgroundColor: Colors.red,
child: const Icon(
Icons.add,
color: Colors.white,
),
),
);
}
Widget _buildUI() {
return ValueListenableBuilder(
valueListenable: _todosBox.listenable(),
builder: (context, box, widget) {
final todosKeys = box.keys.toList();
if (todosKeys.isEmpty) {
return const Center(
child: Text('Aucune tâche pour le moment'),
);
}
return ListView.builder(
itemCount: todosKeys.length,
itemBuilder: (context, index) {
final dynamic key = todosKeys[index];
final Map todo = _todosBox.get(key);
return ListTile(
title: Text(todo["content"]),
subtitle: Text(
DateTime.parse(todo["time"]).toString(),
),
onLongPress: () async {
await _todosBox.delete(key);
},
trailing: Checkbox(
value: todo["isDone"],
onChanged: (value) async {
final updatedTodo = {
"content": todo["content"],
"time": todo["time"],
"isDone": value,
};
await _todosBox.put(key, updatedTodo);
},
),
);
},
);
},
);
}
Future _displayTextInputDialog(BuildContext context) async {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Ajouter une tâche'),
content: TextField(
controller: _textEditingController,
decoration: const InputDecoration(hintText: "Tâche..."),
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Annuler'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () {
if (_textEditingController.text.isNotEmpty) {
_todosBox.add({
"content": _textEditingController.text,
"time": DateTime.now().toIso8601String(),
"isDone": false,
});
_textEditingController.clear();
}
Navigator.pop(context);
},
child: const Text(
'Ajouter',
style: TextStyle(color: Colors.white),
),
),
],
);
},
);
}
}
_todosBox.add({
"content": _textEditingController.text,
"time": DateTime.now().toIso8601String(),
"isDone": false,
});
Critère | Hive (NoSQL) | SQLite (sqflite) | Drift (ORM) |
---|---|---|---|
Performance | 🚀 Très rapide | Bonne | Bonne mais typée |
Structure | Clé-valeur | Relationnelle | Relationnelle typée |
Simplicité | Très simple | Moyenne (SQL à écrire) | Plus complexe (build_runner) |
Idéal pour | Cache, favoris, settings | Données structurées | Projets complexes |