I recently learned about the Flutter framework in my university, and I'm currently working on a school project. I don't understand why my data inside the hive box that I am using seems to be erased everytime I quit and re-run the app.
main.dart:
void main() async{
// hive initialization protocol
await Hive.initFlutter();
Hive.registerAdapter(YogaRoutineAdapter());
yogaExerciseBox = await Hive.openBox<YogaRoutine>('routineBox');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stress B Gone',
theme: ThemeData.light(useMaterial3: true),
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
exercise_regime.dart:
import 'package:flutter/material.dart';
import 'package:mindfulness_app/global_variables.dart';
import 'package:mindfulness_app/yoga_routine.dart';
class ExerciseRegime extends StatefulWidget {
const ExerciseRegime({super.key});
@override
State<ExerciseRegime> createState() => _ExerciseRegimeState();
}
class _ExerciseRegimeState extends State<ExerciseRegime> {
@override
Widget build(BuildContext context) {
List<YogaRoutine> yogaRoutine =
yogaExerciseBox.values.cast<YogaRoutine>().toList();
return Scaffold(
appBar: AppBar(
title: const Text('My regime'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: yogaRoutine.length,
itemBuilder: (context, index) {
return ListTile(
leading: const Icon(Icons.fitbit_sharp),
title: Text(yogaRoutine[index].name),
subtitle: Text(yogaRoutine[index].subtitle),
trailing: IconButton(
onPressed: () {
setState(() {
yogaExerciseBox.deleteAt(index);
});
},
icon: const Icon(Icons.highlight_remove_rounded),
),
);
},
),
),
],
),
);
}
}
code for insertion:
Center(
child: ElevatedButton(
onPressed: () {
YogaRoutine newYogaExercise = YogaRoutine(
name: 'Tree Pose',
subtitle: 'Your daily dose of energy',
);
setState(() {
yogaExerciseBox.put(
'key_${newYogaExercise.name}',
newYogaExercise,
);
});
},
child: const Text("Add to routine"),
),
),
I cannot seem to figure out, if there is something wrong with my implementation using hive or does an emulator wipe all data everytime it is closed.