flutter
/

Dart HTTP – Making HTTP Requests with Examples

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart HTTP – Making HTTP Requests with Examples

Introduction to HTTP in Dart

Making HTTP requests is a common task for any application that communicates with web services. Dart provides the http package, which is a simple, easy‑to‑use library for sending HTTP requests. It supports GET, POST, PUT, DELETE, and other methods, and handles both synchronous and asynchronous operations. This guide will teach you how to use the http package effectively.

First, add the package to your pubspec.yaml:

dependencies:
  http: ^1.2.0

Then run dart pub get to install it.

Basic GET Request

The http.get() function sends a GET request to a URL. It returns a Future<Response>. The response contains status code, headers, and body.

DARTRead-only
1
import 'package:http/http.dart' as http;

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    print('Response body: ${response.body}');
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

GET with Headers

You can add custom headers by passing a headers map.

DARTRead-only
1
var response = await http.get(
  Uri.parse('https://api.example.com/data'),
  headers: {
    'Authorization': 'Bearer your_token',
    'User-Agent': 'Dart App',
  },
);

POST Request

To send data with POST, pass a body (usually a map encoded to JSON or form data).

DARTRead-only
1
import 'dart:convert';

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  var response = await http.post(
    url,
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'title': 'Hello',
      'body': 'This is a post',
      'userId': 1,
    }),
  );

  if (response.statusCode == 201) {
    print('Created: ${response.body}');
  } else {
    print('Error: ${response.statusCode}');
  }
}

PUT and DELETE

DARTRead-only
1
// PUT
var putResponse = await http.put(
  Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
  body: jsonEncode({'title': 'Updated'}),
  headers: {'Content-Type': 'application/json'},
);

// DELETE
var deleteResponse = await http.delete(
  Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
);

Handling JSON Response

Most APIs return JSON. Use jsonDecode from dart:convert to parse the response body.

DARTRead-only
1
import 'dart:convert';

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    List<dynamic> posts = jsonDecode(response.body);
    for (var post in posts) {
      print('Title: ${post['title']}');
    }
  }
}

Error Handling

Always handle network errors and HTTP errors gracefully. Use try/catch and check status codes.

DARTRead-only
1
void main() async {
  try {
    var response = await http.get(Uri.parse('https://example.com/data'));
    if (response.statusCode == 200) {
      // process
    } else {
      print('HTTP error: ${response.statusCode}');
    }
  } catch (e) {
    print('Network error: $e');
  }
}

Using a Client for Multiple Requests

If you need to make multiple requests to the same host, use a Client to reuse a connection and benefit from keep‑alive.

DARTRead-only
1
var client = http.Client();
try {
  var response1 = await client.get(Uri.parse('https://example.com/api/1'));
  var response2 = await client.get(Uri.parse('https://example.com/api/2'));
} finally {
  client.close();
}

Timeout

You can set a timeout on requests to avoid waiting indefinitely.

DARTRead-only
1
var response = await http.get(
  Uri.parse('https://example.com/slow'),
).timeout(Duration(seconds: 5));

Key Takeaways

    • Add the http package to your dependencies.
    • Use http.get(), http.post(), etc., to send requests.
    • Always convert URIs with Uri.parse().
    • Check response.statusCode to handle errors.
    • Use jsonDecode to parse JSON responses.
    • For multiple requests, use a Client for efficiency.
    • Set timeouts to prevent hanging.

Try it yourself

// HTTP requests require a network connection.
// This example is for local testing.
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);
    print('Title: ${data['title']}');
  }
}

Test Your Knowledge

Q1
of 4

Which package is commonly used to make HTTP requests in Dart?

A
dart:http
B
dart:network
C
http
D
flutter_http
Q2
of 4

What method is used to send a POST request with the `http` package?

A
http.get
B
http.post
C
http.send
D
http.request
Q3
of 4

How do you parse a JSON response body?

A
response.json()
B
jsonDecode(response.body)
C
response.parse()
D
decode(response.body)
Q4
of 4

What is the recommended way to handle multiple requests to the same host?

A
Use multiple `http.get` calls
B
Create a `Client` and reuse it
C
Use `Future.wait`
D
Set a timeout

Frequently Asked Questions

Do I need to import `dart:convert` to use `jsonEncode` and `jsonDecode`?

Yes, those functions are part of dart:convert. You must import it when working with JSON.

What if the API returns data in a different format (like XML)?

You'll need to parse the response body accordingly. The http package just gives you the raw string; you can then use an XML parser library.

How do I send form‑urlencoded data?

Set the Content-Type header to application/x-www-form-urlencoded and pass the body as a string with key‑value pairs encoded (e.g., 'key1=value1&key2=value2').

Can I cancel an ongoing request?

The built‑in http package does not support cancellation directly. You can use the Client and cancel the connection by closing it, but that's not fine‑grained. For better control, consider dart:io's HttpClient or third‑party packages.

Is it safe to use `http` in a Flutter app?

Yes, it's safe and widely used. However, for Android, you may need to add internet permission to AndroidManifest.xml. For iOS, add network access to Info.plist (or use App Transport Security settings).

Previous

dart file handling

Next

flutter statefulwidget

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.