No event fired when data is added

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?

Don’t re-assign withdrawals. It is a live realm results and will always contain the latest commit’ted state.

In particular you are overwriting the realm result you are listening to. Since you don’t store the subscription either it becomes eligible for garbage collection, and you stop listening. It is not really related to realm at all.

Anyway, of the top of my head, something like this should work:

  void initState() {
    super.initState();
    subscription.connect();
    _sub = withdrawals.changes.listen((event) {
      print(event);
      setState(() {});
    });
  }

  @override
  void dispose() {
    _sub.cancel();
    super.dispose();
  }
}

but in general I would suggest using a stream builder in a stateless widget instead. As an example you can see here: Realm Query Pagination · Issue #1058 · realm/realm-dart · GitHub

1 Like