projectIdFromCredentialsFile function

String? projectIdFromCredentialsFile()

Returns the Project ID for the current Google Cloud Project by reading the project_id field from the credentials JSON file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable.

This is useful for local development when using a service account JSON file for authentication, as it allows the project ID to be automatically discovered from the credentials file without requiring an additional environment variable.

If the environment variable is not set, the file doesn't exist, or the file is invalid JSON, null is returned.

Implementation

String? projectIdFromCredentialsFile() {
  final path = Platform.environment[credentialsPathEnvironmentVariable];
  if (path == null) return null;

  try {
    final json =
        jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>;
    return json['project_id'] as String?;
  } catch (e) {
    // If file doesn't exist or is invalid, return null
    return null;
  }
}