stringChoiceValueParser<T> function

ValueParser<T> stringChoiceValueParser<T>(
  1. List<T> choices, {
  2. ValuePrinter<T>? printer,
})

Returns a ValueParser that will stringify each choice using the given printer (defaults to toStringValuePrinter()) and returns a value parser that will map a choice's string to the choice value.

var boolValueParser = stringChoiceValueParser([true, false]);
print(boolValueParser('true'));  // returns the boolean `true`
boolValueParser('thing');        // throws an exception

Implementation

ValueParser<T> stringChoiceValueParser<T>(List<T> choices,
    {ValuePrinter<T>? printer}) {
  printer ??= toStringValuePrinter;
  var choiceMap = {
    for (var choice in choices) printer(choice): choice,
  };

  return (s) {
    var choice = choiceMap[s];
    if (choice == null) {
      var formattedChoices = choiceMap.keys.join(', ');
      throw ValueParserException(
          'Value not in available choices: $formattedChoices');
    }

    return choice;
  };
}