These are my models and I'm trying to save some observations related to a certain student using Hive in Flutter:
@HiveType(typeId: 5)
class Student extends HiveObject {
@HiveField(0)
late String firstName;
@HiveField(1)
late String lastName;
@HiveField(2)
HiveList<Observation>? observations;
@HiveField(3)
StudentGroup? studentGroup;
@HiveField(4)
Gender? gender;
}
@HiveType(typeId: 11)
class Observation extends HiveObject {
@HiveField(0)
late String wording;
@HiveField(1)
late DateTime date;
@HiveField(2)
late Rating rating;
@HiveField(3)
late String subject;
}
This is where I save the observations:
class ObservationWidget extends StatefulWidget {
final Student student;
const ObservationWidget({super.key, required this.student});
@override
State<ObservationWidget> createState() => _ObservationWidgetState();
}
class _ObservationWidgetState extends State<ObservationWidget> {
Rating? _selectedRating;
String? _selectedSubject;
DateTime date = DateTime.now();
late TextEditingController textController;
void saveObservation() {
if (_selectedRating == null || _selectedSubject == null) {
// Todo: Add a message
return;
}
final observationsBox = Boxes.getObservations();
final newObservation = Observation()
..date = date
..rating = _selectedRating!
..wording = textController.text
..subject = _selectedSubject!;
observationsBox.add(newObservation);
widget.student.observations = HiveList(Boxes.getObservations());
widget.student.observations!.add(newObservation);
print(widget.student.observations);
print(observationsBox.values);
widget.student.save();
Navigator.of(context).pop();
}
And this is what the console shows after saving an observation:
flutter: [Instance of 'Observation'] flutter: (Instance of 'Observation', Instance of 'Observation', Instance of 'Observation', ..., Instance of 'Observation', Instance of 'Observation')
And here's how I try to load the student's observations:
class ObservationsPage extends StatefulWidget {
final Student student;
const ObservationsPage({super.key, required this.student});
@override
State<ObservationsPage> createState() => _ObservationsPageState();
}
class _ObservationsPageState extends State<ObservationsPage> {
late List<Observation> studentObservations;
@override
void initState() {
studentObservations = widget.student.observations ?? [];
super.initState();
}
This works fine as long as I don't restart. But when I do so, the ObservationPage doesn't show the observations anymore.