projectIdFromGcloudConfig function
Returns a Future that completes with the Project ID for the current Google Cloud Project by querying the gcloud CLI configuration.
Note: this functions runs gcloud config config-helper --format json and
parses the output.
If gcloud is not installed, not in PATH, or fails to execute, null is
returned.
This is useful for local development when developers have authenticated
using gcloud auth application-default login and set their project using
gcloud config set project PROJECT_ID. The project ID is automatically
discovered from the gcloud CLI without requiring additional environment
variables.
Implementation
Future<String?> projectIdFromGcloudConfig() async {
try {
final result = await Process.run('gcloud', [
'config',
'config-helper',
'--format',
'json',
]);
if (result.exitCode != 0) return null;
final stdout = result.stdout;
if (stdout is! String || stdout.isEmpty) return null;
return switch (jsonDecode(stdout)) {
{
'configuration': {
'properties': {'core': {'project': final String project}},
},
} =>
project,
_ => null,
};
} catch (e) {
// If gcloud is not installed or fails, return null
return null;
}
}