Generate idiomatic Dart code to handle an HTTP response using the functional_status_codes package.
{{#http_client}}
The HTTP client in use is: {{http_client}}
{{/http_client}}
{{^http_client}}
Detect the HTTP client from the existing code (look for http.Response, dio.Response, HttpClientResponse, or a plain int status code field).
{{/http_client}}
{{#status_code}} Focus specifically on handling status code {{status_code}} (in addition to general handling). {{/status_code}}
Follow these steps:
-
Extract the status code as
intornumfrom the response object:package:http→response.statusCode(alreadyint)package:dio→response.statusCode(alreadyint?)dart:io HttpClientResponse→response.statusCode(alreadyint)- Custom → use whatever field holds the integer status
-
Apply category-level branching using
maybeWhenStatusCodeormaybeMapStatusCode:- Use
maybeWhenStatusCodewhen the callbacks do not need the code value passed in - Use
maybeMapStatusCodewhen you need(code) =>in the callback - Provide
orElsefor codes outside 100-599 or unhandled categories - Do not provide
isStatusCodealongside category handlers unless you intentionally want it to catch all valid codes first
- Use
-
Drill into specific codes when needed by converting first:
final registered = rawCode.toRegisteredStatusCode(); final result = registered?.maybeMap( orElse: (c) => defaultHandling(c), notFoundHttp404: (_) => handleNotFound(), );
-
Emit null-safe, idiomatic Dart:
- Prefer
?.and??over null-checks - Use
whenConstStatusCode/whenConstOrNullwhen the return values are constants — these accept direct values, not closures (e.g.isSuccess: 'ok', neverisSuccess: () => 'ok'); they must be called on aStatusCodevalue aftertoRegisteredStatusCode()conversion - Avoid
if (code >= 200 && code < 300)— use.isSuccess/.isError/.isCacheableetc.
- Prefer
-
Handle the specific code {{#status_code}}({{status_code}}){{/status_code}} with a dedicated branch inside
maybeMapormaybeWhenon theStatusCode, using the constant name<camelName>Http<NNN>.
Produce a complete, runnable function or method — not just a snippet — with appropriate return type and error handling.