Body class
The body of a request or response.
This tracks whether the body has been read. It's separate from Message because the message may be changed with Message.copyWith, but each instance should share a notion of whether the body was read.
Creating Response Bodies
Text Body
Body.fromString('Hello, World!')
JSON Body
final data = {'name': 'Alice', 'age': 30};
Body.fromString(
jsonEncode(data),
mimeType: MimeType.json,
)
HTML Body
Body.fromString(
'<html><body><h1>Welcome!</h1></body></html>',
mimeType: MimeType.html,
)
Binary Data
final bytes = Uint8List.fromList([1, 2, 3, 4]);
Body.fromData(bytes)
Streaming Data
Stream<Uint8List> dataStream = getFileStream();
Body.fromDataStream(
dataStream,
contentLength: fileSize,
mimeType: MimeType.octetStream,
)
Empty Body
Body.empty()
Reading Request Bodies
Important: The body can only be read once!
// Read as string
final text = await request.readAsString();
// Parse JSON
final data = jsonDecode(await request.readAsString());
// Read as stream
final stream = request.read();
await for (final chunk in stream) {
// Process chunk
}
Constructors
- Body.empty()
-
Creates an empty body.
factory
- Body.fromData(Uint8List body, {Encoding? encoding, MimeType? mimeType})
-
Creates a body from a Uint8List.
factory
-
Body.fromDataStream(Stream<
Uint8List> body, {Encoding? encoding, MimeType? mimeType = MimeType.octetStream, int? contentLength}) -
Creates a body from a Stream of Uint8List.
factory
- Body.fromString(String body, {Encoding encoding = utf8, MimeType? mimeType})
-
Creates a body from a string.
factory
Properties
- bodyType → BodyType?
-
Body type is a combination of
mimeTypeandencoding.final - contentLength → int?
-
The length of the stream returned by read, or
nullif that can't be determined efficiently.final - hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
read(
{int? maxLength}) → Stream< Uint8List> - Returns a Stream representing the body.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited