getUserName function

String? getUserName({
  1. bool throwIfNull = false,
})

Get the local username or null if unknown

Implementation

String? getUserName({bool throwIfNull = false}) {
  Map<String, String> envVars = Platform.environment;
  String? userName;
  String envVarName = '';
  switch (Platform.operatingSystem) {
    case 'linux':
    case 'macos':
      envVarName = 'USER';
      userName = envVars[envVarName];
      break;
    case 'windows':
      envVarName = 'USERNAME';
      userName = envVars[envVarName];
      break;
    default:
      userName = null;
      if (throwIfNull) {
        throw ('Unable to determine username on platform ${Platform.operatingSystem}');
      }
      break;
  }
  if (throwIfNull && userName == null) {
    throw ('Unable to determine your username: please set environment variable $envVarName');
  }
  return userName;
}