How do I tell where the user's home directory is, in Dart?

Identify the OS then use the designated environment variable for that particular OS. You can read the OS/environment variables from platform. For e.g. :

  1. OS : String os = Platform.operatingSystem; Various checks like isLinux, isAndroid are given
  2. Map<String, String> envVars = Platform.environment;

An example:

import 'dart:io' show Platform, stdout;

void main() {
  String os = Platform.operatingSystem;
  String home = "";
  Map<String, String> envVars = Platform.environment;
  if (Platform.isMacOS) {
    home = envVars['HOME'];
  } else if (Platform.isLinux) {
    home = envVars['HOME'];
  } else if (Platform.isWindows) {
    home = envVars['UserProfile'];
  }
  stdout.writeln(home);
}

Home dirs taken from here : http://en.wikipedia.org/wiki/Home_directory


I don't have access to a windows machine, but I found this logic in pub:

  if (Platform.environment.containsKey('PUB_CACHE')) {
    cacheDir = Platform.environment['PUB_CACHE'];
  } else if (Platform.operatingSystem == 'windows') {
    var appData = Platform.environment['APPDATA'];
    cacheDir = path.join(appData, 'Pub', 'Cache');
  } else {
    cacheDir = '${Platform.environment['HOME']}/.pub-cache';
  }

Looks like for Linux and Mac, we can do:

Platform.environment['HOME']

For Windows, it's better to find a location inside of Platform.environment['APPDATA']


This will do:

String get userHome =>
    Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];

Tags:

Dart