write method

Future<bool> write(
  1. String key,
  2. String value
)

Store a value in the system keychain.

Implementation

Future<bool> write(String key, String value) async {
  if (Platform.isMacOS) {
    final result = await Process.run('security', [
      'add-generic-password',
      '-a', key,
      '-s', serviceName,
      '-w', value,
      '-U', // Update if exists
    ]);
    return result.exitCode == 0;
  } else if (Platform.isLinux) {
    final result = await Process.run('secret-tool', [
      'store',
      '--label',
      '$serviceName:$key',
      'service',
      serviceName,
      'account',
      key,
    ], environment: Platform.environment);
    // secret-tool reads the secret from stdin
    if (result.exitCode != 0) {
      // Try with stdin
      final proc = await Process.start('secret-tool', [
        'store',
        '--label',
        '$serviceName:$key',
        'service',
        serviceName,
        'account',
        key,
      ]);
      proc.stdin.writeln(value);
      await proc.stdin.close();
      final code = await proc.exitCode;
      return code == 0;
    }
    return true;
  }
  throw UnsupportedError('SecureStorage is not supported on this platform');
}