setItem method

Future<void> setItem(
  1. String key,
  2. Map<String, dynamic> value, {
  3. bool encrypt = encryptByDefault,
  4. Duration? timeToLive,
  5. Batch? batch,
})

This function will store any data as a single json object in the database. We will try and update the key first and then insert if none exists key the key of your item used to be retrieved later value json Map of your value object encrypt should the value be encrypted (default: false) timeToLive how long should the data be considered valid (default: null) If you getItem and the TTL has expired null will be returned and it will be removed from the database if timeToLive is null the data will never expire batch for transaction control where many setItem operations can be done in batch and commited at the end. see startBatch

Implementation

Future<void> setItem(
  String key,
  Map<String, dynamic> value, {
  bool encrypt = encryptByDefault,
  Duration? timeToLive,
  Batch? batch,
}) async {
  try {
    IV? iv;
    if (encrypt) {
      iv = IV.fromSecureRandom(KeyStorage.IV_LENGTH);
    }
    final metadata = {
      _timeToLiveKey: timeToLive?.inMilliseconds,
      _encryptedKey: encrypt,
      _ivKey: iv?.base64,
    };
    bool doCommit = false;
    if (batch == null) {
      doCommit = true;
      batch = await startBatch();
    }
    final jsonString = await _encodeJson(value, encrypt, iv);
    _upsert(batch, key, jsonString, metadata);

    if (doCommit) {
      await commitBatch(batch);
    }
  } catch (error, stackTrace) {
    throw StorageException(
      'error setting value with key: $key',
      causedBy: error,
      stackTrace: stackTrace,
    );
  }
}