getAndroidVersion static method

Map<String, String?>? getAndroidVersion()

Reads and returns the version from the Android build.gradle file. @returns {Map<String, String?>?} A map with 'versionName' and 'buildNumber', or null if the file is not found/readable, or an empty map if parsing fails.

Implementation

static Map<String, String?>? getAndroidVersion() {
  var gradleFilePath = p.join(
    Directory.current.path,
    'android',
    'app',
    'build.gradle',
  );
  var gradleFile = File(gradleFilePath);

  if (!gradleFile.existsSync()) {
    gradleFilePath = p.join(
      Directory.current.path,
      'android',
      'app',
      'build.gradle.kts',
    );
    gradleFile = File(gradleFilePath);

    if (!gradleFile.existsSync()) {
      return null; // File not found
    }
  }

  try {
    final content = gradleFile.readAsStringSync();

    // First, check for Flutter's variable-based versions
    final variableNameMatch = RegExp(
      r'versionName\s+=\s+flutter\.versionName',
    ).hasMatch(content);
    final variableCodeMatch = RegExp(
      r'versionCode\s+=\s+flutter\.versionCode',
    ).hasMatch(content);

    if (variableNameMatch && variableCodeMatch) {
      return {
        'versionName': 'flutter.versionName',
        'buildNumber': 'flutter.versionCode',
      };
    }

    // If not found, check for hardcoded versions
    final versionNameMatch = RegExp(
      r'versionName\s+"([^"]+)"',
    ).firstMatch(content);
    final versionCodeMatch = RegExp(
      r'versionCode\s+(\d+)',
    ).firstMatch(content);
    if (versionNameMatch != null && versionCodeMatch != null) {
      return {
        'versionName': versionNameMatch.group(1),
        'buildNumber': versionCodeMatch.group(1),
      };
    }
    return {}; // File found but version not parsed
  } on FileSystemException {
    return null; // Error reading file
  }
}