tezvyn:

Dart's `http` Package: Simple Requests vs. Composable Clients

AI-drafted, machine-checkedSource: pub.devbeginner

Dart's `http` package simplifies web requests. Use top-level functions like `http.get()` for one-off calls, or a `Client` for persistent connections. Forgetting to call `client.close()` is a common footgun that leaks resources.

WHY IT EXISTS Dart needs a standard, multi-platform way to communicate with web servers. The http package provides a consistent, Future-based API for making HTTP requests, whether you're building for mobile, desktop, or the browser, abstracting away platform-specific details.

THE MENTAL MODEL Think of the http package as a toolbox for talking to APIs. For a single, quick task, you grab a simple tool off the shelf, like http.get(). For a bigger project with many tasks on the same site, you set up a dedicated workbench, an http.Client instance, that you use repeatedly and then clean up with client.close() when finished.

HOW IT WORKS The package offers two main approaches. First, top-level static functions like http.read() or http.post() are fire-and-forget methods for individual requests. Second, you can create an instance of http.Client. This object manages a persistent connection, which is more efficient for making multiple requests to the same server. You send requests using methods on the client instance, like client.get(). The library is composable, meaning you can wrap a client in another client to add functionality, such as the built-in RetryClient which automatically retries failed requests.

WHEN TO USE IT Use top-level functions (http.get, http.post) for simple scripts or one-off data fetches where setup is overkill. Use a Client instance when your application makes multiple requests to the same API, as it's more performant. Critically, always use a Client instance inside services or classes so you can inject a mock client during testing, which is impossible with the static top-level functions.

WHEN NOT TO USE IT While versatile, for complex scenarios involving heavy streaming, WebSockets, or fine-grained connection-level control, you might need a lower-level library. The http package is designed for common request-response patterns and may be too high-level for specialized network tasks.

ONE CANONICAL EXAMPLE To make multiple requests efficiently, create and close a Client in a try/finally block. This ensures resources are always released.

var client = http.Client(); try { var response = await client.get(Uri.https('example.com', 'data.json')); print(response.body); } finally { client.close(); }

Read the original → pub.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.