tryParse static method

  1. @factory
Unit? tryParse(
  1. String string
)

Convert string to a unit, returning null in case the string couldn't be parsed.

This method and toString() are NOT the opposite of each other. This is intentional, since writing a method that can parse the string returned by toString() is not very easy and this method isn't intended to parse units from the user. Here are the differences:

  • toString() uses ยท as a multiplication symbol, while this method uses *.
  • toString() uses parentheses sometimes, while this method can't parse them.
  • toString() can print powers, while this method can't parse them. You can repeat the units instead.

Implementation

@factory
// ignore: prefer_constructors_over_static_methods
static Unit? tryParse(String string) {
  final unitsUp = <PrefixedBaseUnit>[];
  final unitsDown = <PrefixedBaseUnit>[];

  final list = string.split(RegExp('(?=[*/])'));

  if (!_parseAndAddPrefixedBaseUnitToList(unitsUp, list[0])) {
    return null;
  }

  for (final string in list.skip(1)) {
    final List<PrefixedBaseUnit> list;

    switch (string[0]) {
      case '/':
        list = unitsDown;
        break;

      case '*':
        list = unitsUp;
        break;

      default:
        return null;
    }

    if (!_parseAndAddPrefixedBaseUnitToList(list, string.substring(1))) {
      return null;
    }
  }

  return Unit._derived(unitsUp, unitsDown);
}