I have a preferences class which I want to store and read to/from a database, reading the preferences happen a lot in my application so I want to store an intstance of this preferences object alive in the app. This part is okay but when writing the prefrences back to the database when any changes occur is problematic. I want to access and modify my preferences like a regular object and let the reading/writing on the DB side happen in the background. So I wrote getters and setters for the instance of my object and made it like a Singleton, reading part is okay but when modifying the object the setter isn't invoked.
late final preferencesData _preferences;
preferencesData get preferences {
if (_preferences == null) {
_preferences = preferencesDatabase.get('0',defaultValue: preferencesData(datatypeVersion: appVersion, creationTime: DateTime.now()))!;
}
print('Preferences read');
return _preferences;
}
set preferences(preferencesData val){
preferencesDatabase.put('0', val);
print('Preferences set');
}
In the app when running
print(prefrences.UIsize);
this gets printed
Preferences read
1.3
But when running
preferences.UIsize = 5.0;
print(prefrences.UIsize);
this gets printed
Preferences read
Preferences read
5.0
where as I expect
Preferences read
Preferences set
Preferences read
5.0
My class definition is like:
import 'package:app/3_Datas/1_HiveDataTypes/ColorSerializer.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:json_annotation/json_annotation.dart';
part 'preferencesDataType.g.dart';
@JsonSerializable()
@HiveType(typeId: 5)
class preferencesData extends HiveObject{
@HiveField(0) List<double> versionUpdateList = [1.0];
@HiveField(1) double datatypeVersion;
@HiveField(2) String entryCode = '0';
@HiveField(3) DateTime creationTime;
@HiveField(4) String username = 'user';
@HiveField(5) List<String> yayinlar = ['Yayın ekle+'];
@HiveField(6) double UItextSize = 1.0;
@HiveField(7) double UIappSize = 1.0;
@ColorSerialiser()
@HiveField(8) List<Color> backgroundColors = [
Color.fromARGB(255, 107, 200, 243),Color.fromARGB(255, 58, 124, 201),
Color.fromARGB(255, 192, 45, 113),Color.fromARGB(255, 82, 185, 99),
Color.fromARGB(255, 117, 70, 248),Color.fromARGB(255, 219, 62, 88),
Color.fromARGB(255, 192, 45, 113),Color.fromARGB(255, 82, 185, 99),
Colors.transparent,Colors.transparent
];
@HiveField(9) bool dersModu = false;
@HiveField(10) bool isWelcome = true;
@HiveField(11) bool hasVersionChanged= true;
@HiveField(12) Map<String,int> konuProgress = {};
@HiveField(13) Map<String,dynamic> dataCursors = {};
preferencesData(
{
required this.datatypeVersion,
required this.creationTime,
})
{
}
How can I do this without having to manually write to the DB inside the app code? I am using flutter-hive as DB. Thanks in advance.