valueAsString<T extends String?> static method

T valueAsString<T extends String?>(
  1. Object? value, {
  2. bool allowJson = false,
  3. bool allowHexEncoding = false,
  4. StringEncoding? bytesEncoding = StringEncoding.utf8,
})

Implementation

static T valueAsString<T extends String?>(
  Object? value, {
  bool allowJson = false,
  bool allowHexEncoding = false,
  StringEncoding? bytesEncoding = StringEncoding.utf8,
}) {
  if (value is T) return value;
  if (value == null && _isNull<T>()) return null as T;
  if (value is List<int> && BytesUtils.isBytes(value)) {
    if (bytesEncoding != null) {
      final decode = StringUtils.tryDecode(value, encoding: bytesEncoding);
      if (decode != null) {
        return decode as T;
      }
    }
    if (allowHexEncoding && value.length.isEven) {
      final decode = BytesUtils.toHexString(value);
      return decode as T;
    }
  }
  if (allowJson && (value is List || value is Map)) {
    final decode = StringUtils.tryEncodeJson(value);
    if (decode != null) {
      return decode as T;
    }
  }
  if (value is! String) {
    throw JsonParserError("Failed to parse value as string.");
  }
  return value as T;
}