Sub topic 3
Your first GET request with the http package
A GET request asks a server for data and changes nothing on the server. This chapter shows how to send one from Dart with the http package, read the response, and turn the body into a typed object.
What this chapter assumes
You should already know:
- Dart classes, null safety and named parameters.
Futureandasync/await.- The
StatefulWidgetlifecycle (initState,build). - How to add a package to
pubspec.yaml.
Network permissions for Android, iOS, macOS and web are covered in the previous chapter. If a request fails on a device but works in a plain Dart script, check that chapter first.
Adding the package
Run this command in your project folder:
flutter pub add httpIt adds a line like this to pubspec.yaml. Your version number will differ.
dependencies:
http: ^1.2.0Import it with a prefix. The package exports names such as get, post and Client that are easy to confuse with your own code.
import 'package:http/http.dart' as http;Building the address with Uri
Every request needs a Uri. There are two common ways to build one.
Uri.parse('https://example.com/posts/1')reads a complete string.Uri.https('example.com', '/posts/1')builds the address from parts. The first argument is the host, so do not includehttps://.
Uri.https is the safer choice when any part comes from user input or a variable. It escapes query values for you. Compare the two ways of adding a filter:
void main() {
const userInput = 'a&b=c d';
// Manual string building: the & and space break the query string.
final broken = Uri.parse('https://example.com/search?q=$userInput');
// Query parameters are encoded for you.
final safe = Uri.https('example.com', '/search', {'q': userInput});
print(broken.queryParameters); // {q: a, b: c d}
print(safe.queryParameters); // {q: a&b=c d}
print(safe); // https://example.com/search?q=a%26b%3Dc+d
}Query parameter values must be strings, or iterables of strings for repeated keys. Pass '1', not 1.
The request and its model
The example below uses JSONPlaceholder, a free fake API. The Post class holds only the two fields we need. Extra keys in the JSON, such as userId and body, are ignored.
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) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
Map<String, dynamic> toJson() => {'id': id, 'title': 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}');
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
Future<void> main() async {
final client = http.Client();
try {
final post = await fetchPost(client, 1);
print('${post.id}: ${post.title}');
} finally {
client.close();
}
}Save this as bin/main.dart in a Dart project that depends on http, then run dart run. The same fetchPost function works unchanged inside a Flutter app.
The function does four things in order:
- It builds the
Uri. - It sends the request. The
Acceptheader tells the server which format we want. - It checks
statusCodebefore touching the body. - It decodes the body and builds a
Post.
What happens on the wire
The await on client.get completes when the response headers and body have arrived. The call never returns a partial result.
Reading the Response
client.get returns an http.Response. These members matter most:
| Member | Type | Use |
|---|---|---|
| `statusCode` | `int` | The result of the request, such as 200 or 404. |
| `body` | `String` | The body decoded to text. |
| `bodyBytes` | `Uint8List` | The raw bytes, before any decoding. |
| `headers` | `Map<String, String>` | Response headers. Keys are lowercase. |
| `request` | `BaseRequest?` | The request that produced this response. |
Which text encoding does body use?
The body getter decodes the bytes using the charset in the response's Content-Type header. If the header has no charset, the package falls back to Latin-1. Most JSON APIs send UTF-8 without declaring it, so accented letters, emoji and non-Latin scripts can come out garbled.
When you control the decoding, use the bytes:
final data = jsonDecode(utf8.decode(response.bodyBytes));This is safe whenever the server really sends UTF-8, which the JSON standard requires for network exchange.
Why pass a Client
The package also has top-level helpers such as http.get(uri). Each call opens a connection, makes one request and closes it. They are fine for a quick experiment. For app code, pass an http.Client instead:
- A client can keep connections open and reuse them across requests.
- Code that receives a client as a parameter can be tested with a fake one. A later chapter does this with
MockClient. - You decide when the connection resources are released by calling
client.close().
Create one client for the lifetime of the part of the app that uses it, and close it when that part goes away. Do not create a new client for every request and forget to close it.
Filtering with query parameters and reading lists
Many endpoints return an array instead of one object. The top-level JSON value is then a List, so casting it to Map<String, dynamic> throws a TypeError. Cast to List<dynamic> and map each element.
Future<List<Post>> fetchPostsByUser(http.Client client, int userId) async {
final uri = Uri.https(
'jsonplaceholder.typicode.com',
'/posts',
{'userId': '$userId'},
);
final response = await client.get(uri);
if (response.statusCode != 200) {
throw Exception('Failed to load posts: ${response.statusCode}');
}
final items = jsonDecode(response.body) as List<dynamic>;
return items
.map((item) => Post.fromJson(item as Map<String, dynamic>))
.toList();
}The request goes to /posts?userId=1. Check the shape of the JSON in the API documentation, or print response.body once, before you write the cast.
Calling it from a widget
Start the request once, in initState, and keep the resulting Future in a field. The next chapters build this out with FutureBuilder and its loading and error states. For now, the key rule is where the call lives.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class FirstPostScreen extends StatefulWidget {
const FirstPostScreen({super.key, required this.client});
final http.Client client;
@override
State<FirstPostScreen> createState() => _FirstPostScreenState();
}
class _FirstPostScreenState extends State<FirstPostScreen> {
late final Future<Post> _post;
@override
void initState() {
super.initState();
_post = fetchPost(widget.client, 1);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Post>(
future: _post,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return Center(child: Text(snapshot.data!.title));
},
);
}
}Common errors and what they mean
The argument type 'String' can't be assigned to 'Uri'. Since version 0.13 of the package, request methods take aUri, not a string. Wrap the string withUri.parse.type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>'(or the reverse). The JSON shape differs from your cast. Print the body and compare.type 'Null' is not a subtype of type 'String'insidefromJson. A key is missing or misspelled in the JSON. Use a nullable field andas String?if the field is genuinely optional.SocketExceptionorClientExceptionon a device only. This is usually a missing permission or entitlement. See the platform setup chapter. On a real Android device,localhostpoints at the phone itself. The Android emulator reaches your computer at10.0.2.2.- A
ClientExceptionon Flutter web, with the server working elsewhere. The browser blocked the response because the server did not send CORS headers. You must fix this on the server. The client code cannot work around it. - Garbled non-English text. See the encoding section above.
A non-200 status does not throw by default. client.get completes normally for a 404 or 500, which is why the examples check statusCode themselves. The error handling chapter replaces these bare Exceptions with a dedicated type and adds timeouts.
Summary of the working model
- A GET request needs a
Uri. Build it withUri.httpswhen parts of it vary. client.getreturns aResponseonce the whole reply has arrived. It throws only for connection-level failures, not for HTTP error statuses.- Check
statusCodefirst, then decode withjsonDecodeand convert the result into a model withfromJson. - Pass a shared
http.Clientinto your functions, and close it when you are finished with it. - In a widget, create the
Futureonce ininitState, never inbuild.
Exercise
The endpoint /comments?postId=1 on jsonplaceholder.typicode.com returns a JSON array of comment objects, each with an integer "id" and a string "email". Write a Dart function fetchCommentEmails(http.Client client, int postId) that returns a Future<List<String>> of the emails. Which cast must you use on the decoded JSON, and what must you check before decoding?
Show answer
Build the Uri with Uri.https('jsonplaceholder.typicode.com', '/comments', {'postId': '$postId'}), call client.get, and check that response.statusCode is 200 before decoding, throwing an exception otherwise. The top-level JSON value is an array, so cast the result of jsonDecode to List<dynamic>, not Map<String, dynamic>. Then map each element with (item as Map<String, dynamic>)['email'] as String and call toList(). Example: final items = jsonDecode(response.body) as List<dynamic>; return items.map((item) => (item as Map<String, dynamic>)['email'] as String).toList();