decode method

IndexUnitEnum? decode(
  1. dynamic data, {
  2. bool allowNull = true,
})

Returns the instance of IndexUnitEnum that was successfully decoded from the passed data value on success, null otherwise.

If allowNull is true and the data cannot be decoded successfully, then null is returned. However, if allowNull is false and the data cannot be decoded successfully, then an UnimplementedError is thrown.

The allowNull is very handy when an API changes and a new enum value is added or removed, and users are still using an old app with the old code.

Implementation

IndexUnitEnum? decode(dynamic data, {bool allowNull = true}) {
  if (data is IndexUnitEnum) {
    return data;
  }
  if (data != null) {
    switch (data) {
      case r'percent': return IndexUnitEnum.percent;
      case r'days': return IndexUnitEnum.days;
      default:
        if (!allowNull) {
          throw ArgumentError('Unknown enum value to decode: $data');
        }
    }
  }
  return null;
}