Response class final

Immutable HTTP response (BLUEPRINT_V2 §7.2.3).

Constructors

Response({int status = 200, Headers? headers, ResponseBody body = const EmptyBody(), int? contentLengthOverride, WebSocketHandler? webSocket, bool webSocketCompression = true, int webSocketMaxPayloadBytes = defaultWebSocketMaxPayloadBytes, int webSocketMaxBufferedBytes = defaultWebSocketMaxBufferedBytes, int webSocketSlowClientCode = 1008, Duration webSocketAssembleTimeout = defaultWebSocketAssembleTimeout, int webSocketControlFrameBurst = defaultWebSocketControlFrameBurst, int webSocketControlFramesPerSecond = defaultWebSocketControlFramesPerSecond, Object? exception})
A response with a status, headers and body; the named constructors (Response.json, Response.html...) are the usual way.
Response.back(Request request, {String fallback = '/', String? previous, int? status})
Raw bytes with an explicit content type. Laravel's back(): to the Referer when it is this site, else previous (the session's previous URL), else fallback. A foreign Referer is ignored, so it cannot make this an open redirect.
factory
Response.bytes(List<int> bytes, {required String contentType, int status = 200, Map<String, String>? headers})
A binary response of bytes, with the given content type. bytes become the body as they are, without a copy: do not change them after.
factory
Response.computed(Uint8List bytes, {required String contentType, int status = 200, Map<String, String>? headers})
A binary response of bytes made on another isolate: a PDF, a CSV, an image or a compressed body from Concurrency.runBytes (ADR-031). As Response.bytes, which it is, bytes become the body without a copy, so the buffer moved from the worker is the one written to the socket.
factory
Response.created(Object? data, {String? location})
201 Created JSON response with optional Location header.
factory
Response.html(String html, {int status = 200, Map<String, String>? headers})
HTML response.
factory
Response.json(Object? data, {int status = 200, Map<String, String>? headers, bool phpCompatible = false})
JSON response (application/json). data may contain maps, lists, numbers, strings, booleans, null, DateTime (ISO-8601 UTC), enums and JsonSerializable objects.
factory
Response.noContent({Map<String, String>? headers})
204 No Content.
factory
Response.redirect(String location, {int status = 302})
Redirect response.
factory
Response.sse(Stream<Object?> events, {Object? endStreamWith = '</stream>', Duration? heartbeat = const Duration(seconds: 15), Map<String, String>? headers, int? maxBufferedBytes = defaultSseMaxBufferedBytes})
Server-sent events (Laravel's response()->eventStream()): each item of events (an SseEvent, or a value sent as an update event) is written as it comes, a : keep-alive comment every heartbeat keeps proxies from closing an idle stream, and endStreamWith (</stream>, as Laravel; null for none) closes it. The stream also ends when the server starts draining, so EventSource reconnects elsewhere. A client that went away is noticed at the next event or heartbeat (TCP reports nothing on an idle connection), which then cancels events. A client more than maxBufferedBytes behind gets a retry: line and the end of the stream, so it reconnects instead of the server queueing for it (defaultSseMaxBufferedBytes; null pauses events instead, see sseStream).
factory
Response.stream(Stream<List<int>> stream, {required String contentType, int status = 200, int? contentLength, Map<String, String>? headers})
Streamed body with an explicit content type.
factory
Response.streamJson(Stream<Object?> items, {int status = 200, Map<String, String>? headers, bool phpCompatible = false, String? wrap})
A JSON array of items written as they arrive (Laravel's response()->streamJson()): the same bytes as Response.json of the collected list, in chunks, so a large result set is never held whole. Feed it DB.table('users').lazy() or any stream of encodable values; wrap puts the array under a key, {"data":[...]}, and phpCompatible writes PHP's json_encode() bytes. See jsonArrayBytes.
factory
Response.text(String body, {int status = 200, Map<String, String>? headers})
Plain text response.
factory
Response.webSocket(WebSocketHandler handler, {bool compress = true, int maxPayloadBytes = defaultWebSocketMaxPayloadBytes, int maxBufferedBytes = defaultWebSocketMaxBufferedBytes, int slowClientCode = 1008, Duration assembleTimeout = defaultWebSocketAssembleTimeout, int controlFrameBurst = defaultWebSocketControlFrameBurst, int controlFramesPerSecond = defaultWebSocketControlFramesPerSecond})
Switches the connection to a WebSocket (router.ws returns this after the route's middleware passed); handler gets the socket inside the request's scope. compress false turns permessage-deflate off: no compression state per connection, which matters with many of them. Once more than maxBufferedBytes wait to be sent (the client reads too slowly) the connection is closed with slowClientCode. A message above maxPayloadBytes (all its fragments together) is closed with 1009, one that takes longer than assembleTimeout to arrive, and PING/PONG frames past controlFrameBurst and controlFramesPerSecond, with 1008.
factory

Properties

body → ResponseBody
The body.
final
contentLengthOverride → int?
Content length to advertise when the body was stripped (HEAD requests).
final
exception → Object?
Laravel's $response->exception: what this response was rendered from. An exception never passes through next, so this is how a middleware that used to catch one sees it, and how one wrapping a transaction knows to roll back.
final
hashCode → int
The hash code for this object.
no setterinherited
headers → Headers
The response headers.
final
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
status → int
The status code.
final
webSocket → WebSocketHandler?
Set by Response.webSocket: the server upgrades the connection and hands the socket to this handler.
final
webSocketAssembleTimeout → Duration
How long one message may take to arrive whole (defaultWebSocketAssembleTimeout).
final
webSocketCompression → bool
Whether the WebSocket offers permessage-deflate to clients that ask.
final
webSocketControlFrameBurst → int
PING/PONG frames a client may send at once (defaultWebSocketControlFrameBurst).
final
webSocketControlFramesPerSecond → int
PING/PONG frames per second after the burst (defaultWebSocketControlFramesPerSecond).
final
webSocketMaxBufferedBytes → int
How many bytes (characters, for text frames) may wait to be sent before the WebSocket is closed as a slow client (defaultWebSocketMaxBufferedBytes).
final
webSocketMaxPayloadBytes → int
The largest frame the WebSocket accepts (uncompressed bytes); a larger one fails the connection (defaultWebSocketMaxPayloadBytes).
final
webSocketSlowClientCode → int
The close code a slow client gets: 1008 (policy violation) unless the route says otherwise (the Pusher server sends 4100, which Pusher clients answer by reconnecting after a backoff).
final

Methods

bodyBytes() → Future<List<int>>
Collects the body as bytes (consumes stream bodies).
bodyText() → Future<String>
Collects the body as a UTF-8 string.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited
withCookie(String name, String value, {Duration? maxAge, String path = '/', String? domain, bool secure = false, bool httpOnly = true, String? sameSite = 'lax', bool partitioned = false}) → Response
Copy with a Set-Cookie header added (Laravel's withCookie), in the format Laravel writes. maxAge null makes a session cookie; the defaults are Laravel's (path=/, httponly, samesite=lax). The value is sent as is: Laravel's EncryptCookies is not applied. partitioned adds Partitioned (CHIPS), as Laravel's SESSION_PARTITIONED_COOKIE.
withException(Object error) → Response
Laravel's withException, on a copy: a renderer may answer with a shared response, and requests must not see each other's errors.
withHeader(String name, String value) → Response
Copy with name set to value.
withHeaderList(String name, List<String> values) → Response
Copy with every value of name replaced by values (a multi-valued header such as Set-Cookie); an empty list removes the header.
withHeaders(Map<String, String> values) → Response
Copy with all values set.
withoutBody() → Response
Copy without a body (used for HEAD), keeping the advertised length.
withoutCookie(String name, {String path = '/', String? domain}) → Response
Copy that tells the client to delete the cookie name (Laravel's withoutCookie / Cookie::forget); path and domain must match the ones it was set with.
withStatus(int status) → Response
Copy with a different status.
writeTo(HttpResponse out) → Future<void>
Writes this response to a dart:io HttpResponse and closes it.

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

download(Object fileOrPath, {String? name, Map<String, String>? headers, bool deleteFileAfterSend = false, Request? request}) → Future<Response>
response()->download(): fileOrPath, a File or a path, as an attachment. deleteFileAfterSend removes it once it was sent, for a report made for this request. A missing file is a 404.
encodeJson(Object? data) → String
Encodes data with the framework's JSON conventions.
encodePhpJson(Object? data) → String
The bytes of PHP's json_encode() for data (phpCompatible): escaped slashes and non-ASCII, an empty map as [] (an empty PHP array) and a PhpObject as an object, so const PhpObject('stdClass', {}) is {} as (object) [] is in PHP.
file(Object fileOrPath, {Request? request, String? name, String? contentType, Map<String, String>? headers}) → Future<Response>
response()->file(): shown by the browser. Pass request to answer Range (206), which PDF viewers and iOS media players need, and conditional requests. Never build fileOrPath from user input.

Constants

defaultSseMaxBufferedBytes → const int
How far a server-sent event stream may fall behind its client before it ends with a retry: line (Response.sse): 1 MiB.
defaultWebSocketAssembleTimeout → const Duration
How long a WebSocket message may take from its first byte to its last (all its fragments), unless its route says otherwise: 30 s, enough for a message of 1 MiB over a slow mobile network. Longer is closed with 1008.
defaultWebSocketControlFrameBurst → const int
The PING and PONG frames a WebSocket client may send at once, unless its route says otherwise: 20 (then defaultWebSocketControlFramesPerSecond). More is closed with 1008: each PING is answered, and the answers count toward the send buffer.
defaultWebSocketControlFramesPerSecond → const int
The PING and PONG frames per second after the burst: 5.
defaultWebSocketMaxBufferedBytes → const int
How much a WebSocket may have waiting to be sent, unless its route says otherwise: 4 MiB. A client that reads slower than the server writes (a bad network, a paused tab) made dart:io queue every frame in memory; past this the connection is closed instead (webSocketSlowClientCode) and the client reconnects.
defaultWebSocketMaxPayloadBytes → const int
The largest WebSocket frame a route accepts unless it says otherwise: 1 MiB. dart:io sets no limit of its own (its default is the largest integer unless the build defines dart.io.default.ws.max.payload.length), so one client could make a worker buffer a frame of any size.