Question #187MediumFlutter Basics

What if flutter secure storage and get storage already have a key in the name when you try to write the new data to that key will it overwrite or else throw error ?

#flutter#storage

Answer

Flutter Storage Key Overwriting Behavior

When using Flutter Secure Storage or GetStorage with an existing key, the behavior is straightforward: the new data overwrites the existing value without throwing an error.

Flutter Secure Storage

dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = FlutterSecureStorage();

// Writing data
await storage.write(key: 'auth_token', value: 'token_123');

// Overwriting the same key (no error thrown)
await storage.write(key: 'auth_token', value: 'new_token_456');

// Reading returns the latest value
String? token = await storage.read(key: 'auth_token');
print(token); // Output: new_token_456

GetStorage

dart
import 'package:get_storage/get_storage.dart';

final box = GetStorage();

// Writing data
box.write('username', 'john_doe');

// Overwriting the same key (no error)
box.write('username', 'jane_smith');

// Reading returns the latest value
String? username = box.read('username');
print(username); // Output: jane_smith

Comparison Table

FeatureFlutter Secure StorageGetStorage
Overwrite BehaviorOverwrites silentlyOverwrites silently
Error on DuplicateNoNo
SecurityEncrypted storagePlain storage
PlatformiOS Keychain, Android KeyStoreShared Preferences

Safe Update Pattern

If you need to check before overwriting:

dart
// Check before writing
Future<void> safeWrite(String key, String value) async {
  final storage = FlutterSecureStorage();

  // Check if key exists
  String? existingValue = await storage.read(key: key);

  if (existingValue != null) {
    print('Warning: Overwriting existing value');
  }

  await storage.write(key: key, value: value);
}

Key Management Best Practices

  • Always handle null values when reading
  • Use consistent key naming conventions
  • Document your storage keys in constants
  • Implement versioning for important keys
dart
class StorageKeys {
  static const String authToken = 'auth_token';
  static const String userId = 'user_id';
  static const String refreshToken = 'refresh_token';
}

Remember: Both storage solutions overwrite by default. Implement your own validation logic if you need to prevent accidental overwrites.