Request class

Handles HTTP request processing and response generation for the Finch framework. Request is the core class responsible for processing incoming HTTP requests and generating appropriate responses. It provides a comprehensive API for: Request Processing:

  • HTTP method and URI handling
  • Header and cookie management
  • Query parameter and form data parsing
  • File upload processing
  • Session management Response Generation:
  • Template rendering with Jinja engine
  • JSON and XML response formatting
  • File serving and downloads
  • Redirect handling
  • Error page generation Framework Integration:
  • Asset management (CSS, JS)
  • Multi-language support
  • Security features (CORS, authentication)
  • Database integration helpers
  • Widget system integration Template Engine Features:
  • Jinja2-compatible template syntax
  • Dynamic content injection
  • Layout and partial support The class uses a buffer-based approach for content generation, allowing for efficient string building and content manipulation before sending the final response to the client. Example usage:
// In a controller or route handler:
Future<String> handleRequest() async {
  final data = await service.getData();
  return rq.renderJson(data);
}
// Template rendering:
Future<String> renderPage() async {
  return rq.renderView(
    path: 'user/profile.html',
    params: {'user': currentUser, 'title': 'Profile'},
  );
}

Constructors

Request(HttpRequest _rq)
Constructor to initialize the WebRequest with the given HttpRequest.

Properties

assetManager AssetManager
Manages assets like JavaScript and CSS for rendering.
latefinal
authorization Authorization
currently it just support the Basic Authentication You can develop the Authorization class.
no setter
buffer StringBuffer
getter/setter pair
contentType ContentType
no getter
cookies List<Cookie>
Provides access to the list of cookies included in the request.
no setter
cssRenderId String
CSS render ID for asset management.
getter/setter pair
dataJsId String
Data JavaScript render ID for asset management.
getter/setter pair
endpoint String
Gets the current endpoint, normalized for slashes.
no setter
hashCode int
The hash code for this object.
no setterinherited
headers HttpHeaders
Provides access to the HTTP headers included in the request.
no setter
host String
Retrieves the current hostname from the request URI.
no setter
httpRequest HttpRequest
Provides access to the underlying HttpRequest.
no setter
isApiEndpoint bool
Checks if the current endpoint starts with 'api/'.
no setter
isClosed bool
Indicates whether the response has been closed.
getter/setter pair
isPost bool
Check method is Post
no setter
jsRenderId String
JavaScript render ID for asset management.
getter/setter pair
method String
Provides access to the HTTP method (e.g., GET, POST) used in the request.
no setter
port int
no setter
response HttpResponse
Provides access to the response associated with the request.
no setter
route FinchRoute?
The route associated with the request, if any.
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
session HttpSession
Provides access to the session associated with the request.
no setter
stream HttpRequest
Provides access to the request stream.
no setter
uri Uri
Provides access to the URI of the request.
no setter

Methods

addAsset(Asset asset) AssetManager
Adds a single asset to the asset manager.
addAssets(List<Asset> assets) AssetManager
Adds a list of assets to the asset manager.
addCookie(String key, String value, {Duration? duration, bool safe = true}) → void
Adds or updates a cookie in the response.
addParam(String key, Object? param) Request
Adds a single parameter to the request.
addParams(Map<String, Object?> params) Request
Adds multiple parameters to the request.
addSession(String key, Object value) → void
Adds a value to the session.
addValidator(String formName, Map<String, dynamic> validator) → void
Adds a validator for a specific form.
changeLanguege(String ln) → void
Changes the language based on the given language code ln.
checkForm([String? name]) bool
Validates a form submission by checking the hidden form key and timestamp.
checkFormByValue({String name = 'formChecker', required String? value, int diffDuration = 600}) bool
Validates a form submission by checking the provided value against the session key and timestamp. CSRF protection. name - The name attribute for the hidden input field. Defaults to 'formChecker'. value - The value to be validated against the session key. diffDuration - The maximum allowed duration (in seconds) between the form generation and submission. Defaults to 600 seconds (10 minutes). Returns a bool indicating whether the form submission is valid.
data(String key, {String def = '', bool trim = true}) String
Retrieves the value associated with key from the request data.
dataObject(String key, {dynamic def}) → dynamic
Retrieves the value associated with key as an object from the request data.
dataType<T>(String key, {T? def}) → T
Retrieves the value associated with key from the request data, cast to type T.
dump(dynamic object) Future<String>
fixCookieName(String key) String
formChecker({String? name, bool inputHtml = true}) String
Generates a form checker hidden input field or a random key for form validation.
generateRandomString([int length = 8]) String
Generates a random alphanumeric string of a specified length.
get<T>(String key, {T? def, dynamic trim = true}) → T
Retrieves the value of key cast to type T. Supports type-specific operations.
getAll({List<String> keys = const [], bool trim = true}) Map<String, Object?>
Retrieves form data including fields and files Returns a map with 'fields' and 'files' keys. keys in 'fields' contains form fields and their values. trim indicates whether to trim string values.
getAllData({List<String> keys = const [], bool trim = true}) Map<String, Object?>
Retrieves all parsed request data including GET, POST, and FILE data.
getAllSession() Object
Retrieves all session-related data.
getAssets() List<Asset>
Retrieves the list of assets currently managed by the asset manager.
getCookie(String key, {String def = '', bool safe = true}) String
Retrieves a cookie value from the request.
getFile(String key) → dynamic
Retrieves file data associated with key from the request.
getGlobalEvents() Map<String, Object?>
Retrieves global events and parameters for rendering.
getHeaderFormData() Future<Map>
Retrieves form data from a multipart/form-data request.
getIP() String
Retrieves the client's IP address from the request headers or connection information.
getLanguage() String
Retrieves the current language based on URI, session, or settings.
getParam(String key, {Object? def}) Object?
Retrieves the value of a parameter.
getParams() Map<String, dynamic>
Retrieves all parameters as a map.
getSession(String key, {Object? def = ''}) Object
Retrieves a session value.
getTemplateEnvironment() → Environment
getValidator() Map<String, Object?>
Retrieves the validators map.
hasData(String key) bool
Checks if key exists in the request data.
hasDataValue(String key) bool
Checks if key exists and has a non-empty value in the request data.
hasParam(String key) bool
Checks if a parameter exists.
init() Future<Request>
Initializes the request by setting response headers and parsing data.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onClose(String layout) String
Handles tasks to be performed before closing the response.
parseData() Future<Map>
Parses and returns request data from GET, POST, and file fields.
redirect(String path, {int status = HttpStatus.movedTemporarily, bool checkApiPath = true}) Future<String>
Redirects the response to the given path.
redirectNextUri(Uri uri, {int status = HttpStatus.movedTemporarily, bool checkApiPath = true}) Future<String>
Redirects the response to the given URI and waits for the redirect to complete.
redirectUri(Uri uri, {int status = HttpStatus.movedTemporarily, bool checkApiPath = true}) Future<String>
Redirects the response to the given URI.
removeCookie(String key) → void
Removes a cookie by setting its value to an empty string and expiration to a past date.
removeParam(String key) Request
Removes a parameter from the request.
render({required String path, Map<String, Object?> viewParams = const {}, bool isFile = true, bool toData = false, int status = 200}) Future<String>
Renders a template with the given parameters and configuration.
renderAsync({required String path, Map<String, Object?> viewParams = const {}, bool isFile = true, int status = 200}) String
Renders a template with the given parameters and configuration.
renderData({required Map<String, Object?> data, int status = 200}) Future<String>
Renders a map of data as JSON and sends it in the response.
renderDataParam({int status = 200, Map<String, Object?> data = const {}}) Future<String>
Handles rendering of data with additional parameters and status code.
renderError(int status, {Map<String, Object?> params = const {}, String message = '', bool toData = false}) Future<String>
Renders an error view with the specified status and parameters.
renderHtml({required String html, int status = 200}) Future<String>
Renders an HTML response.
renderListData({required List<Map<String, Object?>> data, int status = 200}) Future<String>
Renders a list of data as JSON and sends it in the response.
renderSocket() String
Renders a socket request. Currently, this method only returns a string. this mean it will make a fake string to wait for socket response.
renderSSE(Stream<SSE> stream, {ContentType? contentType, int status = HttpStatus.ok, Map<String, String>? headers, SSE? finish}) Future<String>
Render SSE (Server-Sent Events) stream to the client. This method sets up the necessary headers for SSE and streams data to the client. The stream function should return a stream of strings to be sent as SSE messages. Each message is formatted according to the SSE protocol. The connection is kept alive until the stream is closed. Returns a Future<String> that completes when the stream is closed.
renderSSEString(Stream<String> stream, {ContentType? contentType, int status = HttpStatus.ok, Map<String, String>? headers}) Future<String>
Render SSE (Server-Sent Events) stream to the client. This method sets up the necessary headers for SSE and streams data to the client. The stream function should return a stream of strings to be sent as SSE messages. Each message is formatted according to the SSE protocol. The connection is kept alive until the stream is closed. Returns a Future<String> that completes when the stream is closed.
renderString({required String text, int status = 200, ContentType? contentType}) Future<String>
Renders a plain text response.
renderTag({required Tag tag, int status = 200, bool toData = false, Map<String, dynamic> data = const {}, bool pretty = false}) Future<String>
Renders a Tag object to HTML and sends it in the response. You can use this method to render any HTML tag or widget that implements the Tag interface. This method converts the Tag to an HTML string and then calls renderView to handle the response. status - The HTTP status code to be used. Default is 200. toData - A flag indicating whether to render the data as a parameter. Default is false. data - A map of parameters to be passed to the template. Default is an empty map. pretty - A flag indicating whether to pretty-print the HTML output. Default is false. Returns a Future<String> containing the rendered HTML string.
renderView({required String path, int status = 200, bool isFile = true, bool toData = false, Map<String, dynamic> data = const {}, bool writeAndClose = true}) Future<String>
after this function everything will be stop and send to client
safe(String input) String
Safely escapes HTML special characters in the input string. <a href="javascript:alert(null)"></a> Will be converted to: &lt;a href=&quot;javascript:alert(null)&quot;&gt;&lt;/a&gt;
setSetting(Map<String, Object?> setting) → void
Sets application-specific settings for the request.
toString() String
A string representation of this object.
override
tryData<T>(String key, {T? def, bool trim = true}) → T?
Retrieves the value of key as a String from the request data. If the value is not found, returns def (default value). This method is used to retrieve string values from the request data.
url(String subPath, {Map<String, String>? params}) String
Constructs a full URL by combining a base URL with a subpath and optional query parameters.
writeAndClose(String layout) Future
Writes the layout to the response and closes it.

Operators

operator ==(Object other) bool
The equality operator.
inherited
operator [](String key) String
Overloads the index operator to return the value for key using data.

Static Properties

errorWidget FinchStringWidget
getter/setter pair
layoutFilters Map<String, Function>
no setter
localEvents Map<String, Object>
Local events map for testing purposes.
final

Static Methods

addLocalLayoutFilters(Map<String, Function> filters) → void