initialize method

Future<void> initialize({
  1. String? encryptionKey,
})

Initializes the StorageService.

This method should be called before using any other methods of the service. If encryptionKey is provided, it enables data encryption.

Implementation

Future<void> initialize({String? encryptionKey}) async {
  if (_isInitialized) {
    debugPrint('StorageService already initialized');
    return;
  }
  try {
    debugPrint('Initializing StorageService...');
    if (kIsWeb) {
      // Web-specific initialization
      _initializeForWeb();
    } else {
      // Mobile and desktop initialization
      await _initializeForNative();
    }

    _box = await Hive.openBox('widget_hydrator');
    debugPrint('Hive box opened: widget_hydrator');
    if (encryptionKey != null && encryptionKey.isNotEmpty) {
      try {
        final key = encrypt.Key.fromBase64(encryptionKey);
        _encrypter = encrypt.Encrypter(encrypt.AES(key));
        debugPrint('Encryption enabled with provided key.');
      } catch (e) {
        debugPrint('🔑❌ Incorrect encryption key provided: $e');
        rethrow;
      }
    } else {
      debugPrint('No encryption key provided. Data will not be encrypted.');
    }
  } catch (e) {
    debugPrint('Failed to initialize StorageService: $e');
    rethrow; // Rethrow to allow caller to handle initialization errors
  }
}