Flutter Sembast 插入或更新

huangapple go评论70阅读模式
英文:

Flutter Sembast insert or update

问题

如何在Flutter中使用sembast库实现如果没有记录则插入,否则更新记录?
我尝试了以下代码:

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());
}

它正常工作。这是正确的解决方案吗,还是还有其他直接的sembast API可用?

sembast

英文:

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

答案1

得分: 8

你应该使用 Record.put 来添加或更新具有给定 ID 的记录。

Future updateOrInsert(User user) async {
  await _userStore.record(user.id).put(_db, user.toMap());
}
英文:

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());
}

huangapple
  • 本文由 发表于 2020年1月3日 20:52:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定