Search code examples
flutterdartsembast

Sembast - remove a value in a map


I have a sembast store that stores map objects. If I want to remove a key in a map, do I have to update the entire map object, or is there a way to remove the key without updating the entire map? The docs are only showing how to remove a record, but not how to remove a field. Since there is a method to update a single field, I think it makes sense to have this feature for other operations.

Example:

// store a map that contains another map
int key = await petStore.add(db, {'name': 'fish', friends : {'cats' : 0, 'dogs' : 0}});

// update just the cats attribute
await petStore.record(key).update{'friends.cats' : 2};

// now I want to (if it is possible) remove the cats attribute without calling
await petStore.record(key).update({'name': 'fish', friends : {'dogs' : 0}})

Solution

  • is there a way to remove the key without updating the entire map?

    Yes similar to Firestore, you can delete a field using the sentinel value FieldValue.delete.

    Using dot (.) you can even reference a nested field. Below is an example to remove the cats key in friends in your example:

    print(await petStore.record(key).get(db));
    // prints {name: fish, friends: {cats: 0, dogs: 0}}
    
    print(await petStore
        .record(key)
        .update(db, {'friends.cats': FieldValue.delete}));
    // prints {name: fish, friends: {dogs: 0}}
    

    For more information, check the doc regarding updating fields