skip to Main Content

I am learning by myself a thing or two about Flutter. Here the problem: i am using a simple sembast DB to store a key. I want to give the user the ability to change it. This is how the DB looks like:

{"version":1,"sembast":1}
{"key":"user_key","value":"random-chars"}

How to properly update the ‘random-chars’ string?

I am trying with put and update functions but my code is generating a new record instead of updating the existing one. Here the codes i have tried:

String dbPath = 'db.db';
DatabaseFactory dbFactory = databaseFactoryIo;

Future replaceKey(String k) async {
    Database db = await dbFactory.openDatabase(dbPath);
    var store = StoreRef.main();
    await store.record('user_key').put(db, k);
    //await store.update(db, k, finder: Finder(filter: Filter.byKey('user_key')));
  }

2

Answers


  1. You can use the update method of the RecordRef object.

    String dbPath = 'db.db';
    DatabaseFactory dbFactory = databaseFactoryIo;
    
    Future replaceKey(String k) async {
      Database db = await dbFactory.openDatabase(dbPath);
    
      var store = StoreRef.main();
    
      await store.record('user_key').update(db, {'value': k});
      await db.close();
    }
    

    sembast update method documentation

    Login or Signup to reply.
  2. I am trying with put and update functions but my code is generating a new record instead of updating the existing one

    I’m not sure what you mean by "generating a new record". My guess is that you are looking directly at the db file content. From an app point of view, the record should indeed get updated. Sembast use an append only format that get compacted at some point. This is explained here: https://github.com/tekartik/sembast.dart/blob/master/sembast/doc/storage_format.md

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search