I am using flutter realm to store data on an android device.
import 'package:realm/realm.dart';
import 'model/withdrawal.dart';
class WithdrawalService {
final Configuration _config = Configuration.local([Withdrawal.schema]);
late Realm _realm;
WithdrawalService() {
openRealm();
}
openRealm() {
_realm = Realm(_config);
}
closeRealm() {
if (!_realm.isClosed) {
_realm.close();
}
}
RealmResults<Withdrawal> getWithdrawals() {
return _realm.all<Withdrawal>();
}
Future<bool> addWithdrawal(data) async {
final withdrawal = _realm.query<Withdrawal>('id == "${data['id']}"');
try {
DateTime createdAt = DateTime.parse(data['created_at']).toLocal();
DateTime updatedAt = DateTime.parse(data['updated_at']).toLocal();
if (withdrawal.isEmpty) {
_realm.write(() {
_realm.add(
Withdrawal(
data['id'],
data['user_id'],
data['user']['username'],
data['amount'] is int
? data['amount'].toDouble()
: (data['amount'] is String
? double.tryParse(data['amount'])
: data['amount']),
data['user']['balance'] is int
? data['user']['balance'].toDouble()
: (data['user']['balance'] is String
? double.tryParse(data['user']['balance'])
: data['user']['balance']),
data['confirmed'] == 0 ? false : true,
data['processed'] == 0 ? false : true,
updatedAt,
createdAt,
),
);
});
} else {
_realm.write(() {
withdrawal[0].confirmed = data['confirmed'] == 0 ? false : true;
withdrawal[0].processed = data['processed'] == 0 ? false : true;
withdrawal[0].updatedAt = updatedAt;
});
}
return true;
} catch (e) {
print(e);
return false;
}
}
}
In a widget class, I have var withdrawals = WithdrawalService().getWithdrawals();
and the initState is as follows:
void initState() {
super.initState();
subscription.connect();
withdrawals.changes.listen((event) {
print(event);
setState(() {
withdrawals = WithdrawalService().getWithdrawals();
});
});
getWithdrawals();
}
When I call WithdrawalService().addWithdrawal(data)
in another class, there are no changes in the widget. What could be the problem?