FlutterIntermediate 2 min read

Flutter HTTP requests with status and timeout handling

Separate request execution from JSON parsing, inspect response status and make timeout behavior explicit.

On this page

A successful network connection does not imply a valid application response. Check status, parse the expected payload and keep transport errors distinct from invalid data.

Put the request at a boundary

Add the http package to a local project and import package:http/http.dart as http. The function below accepts a client and endpoint, which makes a fake response easier to supply in a test. The caller owns the client and closes it when no longer needed.

Decide how failures reach the interface

The data function should preserve enough information for a useful higher-level decision. A screen can translate that failure into a short message and retry action. Do not silently turn every failure into an empty collection.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

Future<String> fetchBody(http.Client client, Uri endpoint) async {
  final response = await client.get(endpoint)
      .timeout(const Duration(seconds: 12));
  if (response.statusCode != 200) {
    throw StateError('Request failed: ${response.statusCode}');
  }
  return response.body;
}

Read the result

TimeoutException, a transport exception and an unexpected status describe different cases. The function returns raw text so parsing can be tested separately. Browser requests must also satisfy the remote service’s CORS policy.

Keep four outcomes separate

A transport failure means the request did not complete as intended. An unsuccessful HTTP status is a response from the service. Invalid JSON is a payload problem. Valid data containing no records is a successful empty result. Collapsing all four into an empty list hides the action the user or developer needs to take.

The injected client makes these cases controllable in a test. The caller that owns that client also owns its lifecycle; creating one for every build or forgetting to close a long-lived client obscures resource use.

Continue with JSON validation after checking the response. Use async UI to show the outcome without putting raw exceptions or request logic directly into widget rendering.

Practice and verification

Test a 200 response, a 500 response, invalid JSON and a delayed response. The interface should distinguish “no items” from “could not fetch items”. Never embed a private API key in a public client application.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.