removePlistKey method

OperationResult removePlistKey(
  1. String key
)

Removes a key-value pair from the iOS Info.plist file.

Implementation

OperationResult removePlistKey(String key) {
  final plistFile = File(_infoPlistPath);

  if (!plistFile.existsSync()) {
    return const Failure(
      'Could not find Info.plist. '
      'Are you in a Flutter project root directory?',
    );
  }

  try {
    String content = plistFile.readAsStringSync();

    // Pattern to match the key and its value (handles different value types)
    final keyValuePattern = RegExp(
      r'\s*<key>' +
          RegExp.escape(key) +
          r'</key>\s*(?:<string>[^<]*</string>|<true/>|<false/>|<integer>\d+</integer>|<array>[\s\S]*?</array>)',
      multiLine: true,
    );

    if (!keyValuePattern.hasMatch(content)) {
      return Failure('Key "$key" not found in Info.plist.');
    }

    content = content.replaceFirst(keyValuePattern, '');

    // Clean up any double newlines
    content = content.replaceAll(RegExp(r'\n\s*\n\s*\n'), '\n\n');

    plistFile.writeAsStringSync(content);
    return Success('Successfully removed "$key" from Info.plist.');
  } on FileSystemException catch (e) {
    return Failure('Failed to update Info.plist: ${e.message}');
  }
}