decode<T> method
Null safety
Decodes this object's bytes as T
.
This method will select the Codec for contentType from the CodecRegistry.
The bytes of this object will be decoded according to that codec. If the codec
produces a value that is not T
, a bad request error Response is thrown.
T
must be a primitive type (String, int, double, bool, or a List or Map containing only these types).
An error is not thrown if T is not one of these types, but compiled Conduit applications may fail at runtime.
Performance considerations:
The decoded value is retained, and subsequent invocations of this method return the retained value to avoid performing the decoding process again.
Implementation
Future<T> decode<T>() async {
if (hasBeenDecoded) {
return _cast<T>(_decodedData);
}
final codec =
CodecRegistry.defaultInstance.codecForContentType(contentType);
final originalBytes = await _readBytes(bytes);
if (retainOriginalBytes) {
_bytes = originalBytes;
}
if (codec == null) {
_decodedData = originalBytes;
return _cast<T>(_decodedData);
}
try {
_decodedData = codec.decoder.convert(originalBytes);
} on Response {
rethrow;
} catch (_) {
throw Response.badRequest(
body: {"error": "request entity could not be decoded"},
);
}
return _cast<T>(_decodedData);
}