valueAsBytes<T extends List<int>? > static method
T
valueAsBytes<T extends List<int>? >(
- Object? value, {
- bool allowHex = true,
- StringEncoding? encoding,
- bool allowJson = false,
Implementation
static T valueAsBytes<T extends List<int>?>(
Object? value, {
bool allowHex = true,
/// string encoding
StringEncoding? encoding,
bool allowJson = false,
}) {
if (value == null && _isNull<T>()) return null as T;
if (value is List) {
try {
return value.cast<int>().asBytes as T;
} catch (_) {
throw JsonParserError("Failed to parse value as bytes.");
}
}
if (value is String) {
if (allowHex && StringUtils.isHexBytes(value)) {
final toBytes = BytesUtils.tryFromHexString(value);
if (toBytes != null) return toBytes as T;
}
if (encoding != null) {
final toBytes = StringUtils.tryEncode(value, encoding: encoding);
if (toBytes != null) return toBytes as T;
throw JsonParserError("Failed to parse value as bytes.");
}
}
if (allowJson && (value is List || value is Map)) {
final toBytes = StringUtils.tryEncodeJson(value);
if (toBytes != null) return toBytes as T;
}
throw JsonParserError("Failed to parse value as bytes.");
}