Sub topic 3
Your first GET request with the http package
This chapter assumes you know Dart classes, null safety, named parameters, Future, and async/await. It also assumes you can add a package to pubspec.yaml and understand the basic StatefulWidget lifecycle.
A GET request asks a server to return a resource. The http package provides a Dart client for sending this request and receiving an HTTP response. The response includes a status code, headers, and a body. The body often contains JSON, a text format for structured data.
The request and response flow
A useful working model is:
Uri is Dart’s structured representation of a URL. Prefer Uri.https or Uri.http over manually joining strings. These constructors handle URL components more safely.
The http.Client object sends requests. Injecting a client into your function makes the function easier to test later because a test can provide a fake client.
Build a GET request
Add the package to pubspec.yaml:
dependencies:
http: ^1.2.0Then run flutter pub get. The following program requests post 1 from JSONPlaceholder:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({
required this.id,
required this.title,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'] as int,
title: json['title'] as String,
);
}
final int id;
final String title;
}
Future<Post> fetchPost(http.Client client, int id) async {
final uri = Uri.https(
'jsonplaceholder.typicode.com',
'/posts/$id',
);
final response = await client.get(
uri,
headers: {'Accept': 'application/json'},
);
if (response.statusCode != 200) {
throw Exception(
'Failed to load post: ${response.statusCode}',
);
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
return Post.fromJson(json);
}
Future<void> main() async {
final client = http.Client();
try {
final post = await fetchPost(client, 1);
print('${post.id}: ${post.title}');
} finally {
client.close();
}
}jsonDecode converts the response text into Dart values. The cast tells Dart that this particular JSON value should be a map with string keys. Post.fromJson then converts that map into a typed Post object.
The status code must be checked before decoding. A server can return an error page or an error-shaped JSON object with status 404 or 500. Treating every response as a successful post hides the real problem.
| Status code | Meaning | Typical GET handling |
|---|---|---|
| 200 | The request succeeded | Decode the response body |
| 404 | The resource was not found | Show or throw a not-found error |
| 500 | The server failed | Report a server error and avoid decoding as normal data |
The Accept header tells the server which response format the client prefers. It does not authenticate the request and does not guarantee that the server will honor the preference.
For a Flutter screen, keep the request outside build. A widget may rebuild many times. Creating the future inside build can send the same GET request repeatedly. Create it once in initState, then pass that future to FutureBuilder when connecting the request to the UI.
Exercise
Why should fetchPost receive an http.Client instead of creating one internally?
Show answer
The caller controls the client lifetime, and tests can inject a mock client without using the real network.