Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Sembast insert or update

Tags:

flutter

dart

How to implement insert if no records with the id else update with sembast library in flutter? I tried the below.

Future updateOrInsert(User user) async {
    final result = await update(user);
    if(result == 0){
      insert(user);
    }
 }

 Future update(User user) async {
    final finder = Finder(filter: Filter.byKey(user.id));
    final result = await _userStore.update(await _db, user.toMap(), finder: finder);
    return result;
 }

 Future insert(User user) async {
    await _userStore.add(await _db, user.toMap());
 }

It's working fine. Is this the right solution or is there any other direct sembast APIs available?

sembast

like image 649
krishnakumarcn Avatar asked Nov 29 '25 20:11

krishnakumarcn


1 Answers

You should use Record.put to either add or update a record with a given id.

Future updateOrInsert(User user) async {
  await _userStore.record(user.id).put(_db, user.toMap());
}
like image 140
alextk Avatar answered Dec 01 '25 11:12

alextk