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 theRefererwhen it is this site, elseprevious(the session's previous URL), elsefallback. A foreignRefereris 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.bytesbecome 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
bytesmade on another isolate: a PDF, a CSV, an image or a compressed body fromConcurrency.runBytes(ADR-031). As Response.bytes, which it is,bytesbecome 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 CreatedJSON response with optionalLocationheader.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).datamay 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 ofevents(an SseEvent, or a value sent as anupdateevent) is written as it comes, a: keep-alivecomment everyheartbeatkeeps proxies from closing an idle stream, andendStreamWith(</stream>, as Laravel;nullfor none) closes it. The stream also ends when the server starts draining, soEventSourcereconnects elsewhere. A client that went away is noticed at the next event or heartbeat (TCP reports nothing on an idle connection), which then cancelsevents. A client more thanmaxBufferedBytesbehind gets aretry:line and the end of the stream, so it reconnects instead of the server queueing for it (defaultSseMaxBufferedBytes; null pauseseventsinstead, see sseStream).factory -
Response.stream(Stream<
List< stream, {required String contentType, int status = 200, int? contentLength, Map<int> >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
itemswritten as they arrive (Laravel'sresponse()->streamJson()): the same bytes as Response.json of the collected list, in chunks, so a large result set is never held whole. Feed itDB.table('users').lazy()or any stream of encodable values;wrapputs the array under a key,{"data":[...]}, andphpCompatiblewrites PHP'sjson_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.wsreturns this after the route's middleware passed);handlergets the socket inside the request's scope.compressfalse turns permessage-deflate off: no compression state per connection, which matters with many of them. Once more thanmaxBufferedByteswait to be sent (the client reads too slowly) the connection is closed withslowClientCode. A message abovemaxPayloadBytes(all its fragments together) is closed with 1009, one that takes longer thanassembleTimeoutto arrive, and PING/PONG frames pastcontrolFrameBurstandcontrolFramesPerSecond, 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 throughnext, 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-Cookieheader added (Laravel'swithCookie), in the format Laravel writes.maxAgenullmakes a session cookie; the defaults are Laravel's (path=/,httponly,samesite=lax). The value is sent as is: Laravel'sEncryptCookiesis not applied.partitionedaddsPartitioned(CHIPS), as Laravel'sSESSION_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
nameset tovalue. -
withHeaderList(
String name, List< String> values) → Response -
Copy with every value of
namereplaced byvalues(a multi-valued header such asSet-Cookie); an empty list removes the header. -
withHeaders(
Map< String, String> values) → Response -
Copy with all
valuesset. -
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'swithoutCookie/Cookie::forget);pathanddomainmust 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:ioHttpResponse 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, aFileor a path, as an attachment.deleteFileAfterSendremoves it once it was sent, for a report made for this request. A missing file is a 404. -
encodeJson(
Object? data) → String -
Encodes
datawith the framework's JSON conventions. -
encodePhpJson(
Object? data) → String -
The bytes of PHP's
json_encode()fordata(phpCompatible): escaped slashes and non-ASCII, an empty map as[](an empty PHP array) and a PhpObject as an object, soconst 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. Passrequestto answerRange(206), which PDF viewers and iOS media players need, and conditional requests. Never buildfileOrPathfrom 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:ioqueue 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:iosets no limit of its own (its default is the largest integer unless the build definesdart.io.default.ws.max.payload.length), so one client could make a worker buffer a frame of any size.