getUserInput<T> method

T getUserInput<T>({
  1. required String helpPhrase,
  2. required T defaultValue,
})

Поддерживаемые типы: String, boolean, integer

Implementation

T getUserInput<T>({required String helpPhrase, required T defaultValue}) {
  stdout.write("$helpPhrase [$defaultValue]:  ");
  String output = stdin.readLineSync() ?? "";
  if (defaultValue is bool) {
    output = output.toLowerCase();
  }
  output = output.trim();
  if (defaultValue is bool) {
    return output.isNotEmpty
        ? (output == 'true' || output == 't') as T
        : defaultValue;
  }
  if (defaultValue is int) {
    return (int.tryParse(output) ?? defaultValue) as T;
  }
  if (defaultValue is String) {
    return output.isNotEmpty ? output as T : defaultValue;
  }
  throw UnsupportedError("Тип не поддерживается");
}