Integrating Flutter REST API With Example
Most Flutter apps talk to a backend, and REST remains the most common way to do it. Whether you are fetching a product list, posting a login form, or syncing user data, the pattern is the same: send an HTTP request, parse the JSON response, and update the UI. Getting this right early saves hours of debugging later.
This guide walks through a practical integration using the `http` package: setting up a service layer, handling loading and error states, parsing JSON safely, and avoiding the common pitfalls that cause slow screens or crashes. We will also compare HTTP clients and look at when to reach for something more advanced.
Choosing your HTTP client
For most projects, the `http` package is enough. It is maintained by the Dart team, works on every platform Flutter supports, and has a small API surface. You create a `Client`, call `get` or `post`, and read `response.body`. For simple CRUD against a JSON API, you will rarely need more.
The `dio` package adds interceptors, request cancellation, form data, and built-in retry logic. If your app needs auth token refresh across many endpoints or upload progress, dio can save boilerplate. But adding it for a single GET request is overkill. Start with `http`; migrate when you feel the friction.
A third option is `chopper`, which generates typed clients from an interface. It is useful in large teams where API contracts change often, but it adds build_runner to your workflow. For a typical app with fewer than 20 endpoints, hand-written service classes are easier to read and debug.
- `http`: simple, official, good for most apps
- `dio`: interceptors, cancellation, progress, retries
- `chopper`: code-generated clients for large API surfaces
- Avoid `HttpClient` directly unless you need low-level control
Setting up a service layer
Do not call `http.get` inside your widgets. Create a service class that owns the base URL, headers, and error mapping. A typical service has methods like `fetchProducts()` and `createOrder()`, each returning a typed model or throwing a custom exception. This keeps widgets focused on UI and makes testing straightforward.
Use a constant for the base URL and switch it per environment. In debug builds, point to a staging server; in release, use production. You can read from `--dart-define` at build time: `const String.fromEnvironment('API_BASE')`. This avoids hardcoding URLs and makes CI builds predictable.
Add a default timeout. The `http` package does not set one, so a flaky network can leave a spinner running for minutes. Wrap calls with `.timeout(Duration(seconds: 10))` and catch `TimeoutException`. Ten seconds is a sensible default for mobile; go up to 20–30 seconds for large uploads or slow regions.
| Client | Setup effort | Interceptors | Request cancellation | Best for |
|---|---|---|---|---|
| http | Low | No | No | Small to medium apps, simple CRUD |
| dio | Medium | Yes | Yes | Auth refresh, uploads, complex APIs |
| chopper | High | Yes | Yes | Large teams, many endpoints |
| HttpClient (dart:io) | Medium | No | Limited | Low-level control, no dependencies |
| graphql (ferry) | High | Yes | Yes | GraphQL backends, typed queries |
Parsing JSON safely
`jsonDecode` returns `dynamic`, and casting blindly is the fastest way to crash on a malformed response. Write a `fromJson` factory on each model that checks types and provides fallbacks. For example, `json['price'] as num? ?? 0` prevents a null crash when the backend omits a field during an incident.
For lists, guard against the response being an object instead of an array. A common pattern is `final data = jsonDecode(body); final list = data is List ? data : data['items'] as List;`. This handles APIs that wrap results in pagination envelopes without extra code paths in your UI.
If your models grow beyond a handful of fields, consider `json_serializable`. It generates the `fromJson` and `toJson` code, reducing typos. The trade-off is build_runner time, typically 5–15 seconds per change on a mid-range laptop. For small models, hand-written factories are faster to iterate on.
- Always check the runtime type before casting
- Use `as num? ?? 0` style fallbacks for numbers
- Handle both raw lists and wrapped objects
- Log the raw body on parse errors to speed up debugging
Handling loading, error, and empty states
Every network call has at least four states: loading, success, empty, and error. Build a small `ApiState<T>` sealed class or use a state management solution with explicit states. In the widget, switch on the state to show a spinner, the data, an empty message, or a retry button. This prevents the classic bug where an error shows an empty list.
Show errors that users can act on. A 401 means the session expired; a 500 means try again later; a timeout means check your connection. Map status codes to short messages rather than dumping the raw exception. Keep a debug log with the full response for yourself, but never show stack traces in production.
For retries, limit to one or two automatic attempts with a short delay. Infinite retries drain battery and can hammer a struggling backend. A simple rule: retry on timeout and 5xx, but not on 4xx except 429, where you should respect the `Retry-After` header if present.
A complete example
The example below fetches a list of products from a public test API. It defines a `Product` model, a `ProductService` with a timeout and status check, and a `FutureBuilder` that renders loading, error, and data states. You can paste it into a new Flutter project and run it as-is.
Notice the status code check before decoding. `response.statusCode == 200` is not enough for all APIs; some return 201 for created resources or 204 for empty responses. Handle the codes your backend actually returns, and treat anything outside 200–299 as an error with the body included in the exception message.
The `FutureBuilder` is fine for a single screen, but for anything with refresh or pagination, move the future into a stateful widget or a state manager. Otherwise, every rebuild re-triggers the request, which is a common source of duplicate calls and rate-limit errors.
- Define models with explicit `fromJson`
- Check status codes before decoding
- Set a timeout on every request
- Render loading, error, empty, and data states
Performance and production tips
Reuse a single `http.Client` across requests. Creating a new client per call prevents connection reuse, adding 100–300 ms per request on mobile networks. Store the client in your service class and close it when the service is disposed. With dio, the same applies to `Dio` instances.
Cache responses where it makes sense. A simple in-memory cache with a 5–10 minute TTL cuts duplicate calls when users navigate back and forth. For images and large payloads, use disk caching. Do not cache authenticated endpoints unless you scope the cache per user and clear it on logout.
Compress request and response bodies with gzip where supported; JSON compresses well, often 60–80% smaller. Most servers enable it by default, but check your headers. Also paginate list endpoints: loading 1,000 items at once adds seconds of parse time and memory pressure, while 20–50 per page keeps the UI responsive.
Key points
- Keep HTTP calls in a service layer, not in widgets.
- Always set a timeout and check status codes before decoding.
- Render loading, error, empty, and data states explicitly.
- Reuse one client and cache responses to cut request time by half or more.
Flutter Screen Widget and Cost Estimator
Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.
Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.