1

I always get a new object inserted rather than updating a old object in the database which I observed using Isar Inspector.

Future<void> updateinvstatus(bool x) async {
    final isar = await db;
    final cflist = await isar.cfs.where().findAll();
    final cf = cflist.last;
    cf
      ..end = DateTime.now()
      ..status = x;
    await isar.writeTxn(() async {
      await isar.cfs.put(cf);
    });
  }

I would be grateful for suggestions. I'm a beginner in programming as a whole and flutter.

1 Answers1

0

One thing to keep in mind is that put will update an object if it already exists and insert a new one if it doesn't. Based on its main key, an object's existence is verified. In your situation, if the primary key of cf is not properly set, it may always be interpreted as a new object, resulting in insertion rather than updating. This could be the main reason why you're having problems.

Future<void> updateinvstatus(bool x) async {
  final isar = await db;
  final cflist = await isar.cfs.where().findAll();
  final cf = cflist.last;
  final lastId = cf.id; // assuming 'id' is a property of your 'cf' object

  final objectToUpdate = await isar.cfs.where().idEqualTo(lastId).findFirst();

  if (objectToUpdate != null) {
    objectToUpdate
      ..end = DateTime.now()
      ..status = x;
  
    await isar.writeTxn(() async {
      await isar.cfs.put(objectToUpdate);
    });
  }
}
Hassan Serhan
  • 392
  • 3
  • 13
  • Is there a way to get 'id' of the last object and query the object using that 'id' then updating it? I tried something but didn't work. Thanks for reply @Hassan Serhan – Abash Paudel Jun 05 '23 at 08:46
  • I've update the code in my answer, in the above code, we get the id of the last object, use it to query that object in the database, update it, and then put it back into the database. If the object does not exist, nothing happens. @AbashPaudel – Hassan Serhan Jun 05 '23 at 09:42
  • Thanks, Hassan! I tried that already, but I think I'm calling the method in a wrong way. I have a class called IsarService which contains all the methods for creating and updating the db. I'm using get_it and get_it_mixin for state management. So, how should I consume this method in the UI using these packages? – Abash Paudel Jun 06 '23 at 01:59
  • And also when I tried, replacing 'lastid' with 1, which is the id of the object currently stored in database and exists as I viewed it in isar inspector, still new object gets created instead being updated. I don't know what else to do? – Abash Paudel Jun 06 '23 at 05:48