Sub topic 10
Inspecting HTTP traffic with the Network view
This chapter assumes you can launch DevTools and connect it to a running app, and that you know the difference between debug and profile mode. It also assumes you have used package:http or dart:io to make a request and handle a Future. The Network view shows what your app sent and received, so you can separate client bugs from server bugs.
What the Network view records
The Network view lists the HTTP and HTTPS requests that your Dart code makes. It also lists WebSocket connections. It works by asking the Dart VM, through the VM service, for profiling data about dart:io traffic. That tells you what it can and can't see:
- It sees requests made through
dart:io'sHttpClient.package:httpusesHttpClienton mobile and desktop, so those requests appear. Packages built on top ofHttpClient(such asdiowith its default adapter) appear too. - It does not see traffic that bypasses
dart:io. Examples are native HTTP stacks that some plugins use (for instancecronet_httporcupertino_http), aWebView, and any native SDK your app embeds. - It needs a connection to the VM service, so it works in debug and profile mode. It does not work against a release build.
- On Flutter web, the browser makes the requests. Use the browser's own Network panel instead.
If a request you expect is missing, first check whether it goes through dart:io. Don't assume the request was never sent.
Opening the view and reading the table
Start the app with flutter run (debug is fine for network work), open DevTools, and select the Network tab. Recording starts when the view opens. Use the pause control to stop recording and the clear control to empty the table. Clear it before each experiment so you only see the requests you caused. Requests made before you opened the view may not appear, so open the view before you trigger the behavior you are studying. If you are debugging startup traffic, restart the app with DevTools already open.
Each row in the table is one request. The main columns are:
| Column | What it tells you |
|---|---|
| Request | The URI, shortened to fit the column |
| Method | `GET`, `POST`, `PUT`, `DELETE`, and so on |
| Status | The HTTP status code, or a pending or error state |
| Type | The content type, such as `json` or `image` |
| Duration | Total time from start to the last byte |
| Time | When the request started relative to the recording |
You can sort by any column, and you can filter by text to find requests by URI, method, status, or type. Sorting by Duration finds the slowest request fast. Sorting by Status groups the failures together.
Inspecting one request
Select a row to open its details. Depending on your DevTools version, you get these tabs:
- Headers: general information (URI, method, status code), the request headers, and the response headers.
- Request: the body your app sent, for
POSTandPUTcalls. - Response: the body the server returned. JSON is shown formatted, and images are rendered.
- Cookies: cookies sent and received.
- Timing: how long the connection setup and the request and response phases took.
The tabs answer different questions. Use this table to choose where to look first.
| Question | Where to look |
|---|---|
| Did the request leave the app at all? | Whether a row exists |
| Did it go to the right URL? | Request column and Headers |
| Did the auth token go along? | Request headers (`Authorization`) |
| Did I send the body I intended? | Request tab |
| What did the server actually say? | Status, then Response tab |
| Is the server slow, or is the network slow? | Timing tab |
A worked example
The following app loads a list of posts and shows their titles. It uses package:http. Add it first with flutter pub add http. On macOS, the app also needs the outgoing network client entitlement. Android and iOS debug builds work without changes.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MaterialApp(home: PostsPage()));
class PostsPage extends StatefulWidget {
const PostsPage({super.key});
@override
State<PostsPage> createState() => _PostsPageState();
}
class _PostsPageState extends State<PostsPage> {
// The Future is created once, so rebuilds do not send new requests.
late final Future<List<dynamic>> _posts = _fetchPosts();
Future<List<dynamic>> _fetchPosts() async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts');
final response = await http.get(uri);
if (response.statusCode != 200) {
throw Exception('Request failed with status ${response.statusCode}');
}
return jsonDecode(response.body) as List<dynamic>;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Posts')),
body: FutureBuilder<List<dynamic>>(
future: _posts,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final posts = snapshot.data!;
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, i) =>
ListTile(title: Text(posts[i]['title'] as String)),
);
},
),
);
}
}Run it with flutter run, open the Network view, clear the table, and hot restart the app. Hot reload keeps the existing State object, so the Future is not created again and no request fires. A restart creates new state and sends the request. You should see one GET row for /posts with status 200 and type json. Select it and open the Response tab to confirm that the body holds a list of 100 objects.
Reproducing a failing request
Change the path to /postz and restart. The row now shows status 404. The app shows the error text from the exception. The Network view tells you more than the app does: you can see the exact URI that was requested, and you can read the response body to learn whether the server explained the failure. Change the path back when you are done.
Common problems the Network view exposes
Duplicate requests
If you see the same GET repeated many times, a widget is probably creating the Future inside build:
// Avoid: this sends a new request on every rebuild.
FutureBuilder<List<dynamic>>(
future: _fetchPosts(),
builder: (context, snapshot) { /* ... */ },
)Any setState, theme change, or parent rebuild runs build again and calls _fetchPosts() again. Store the Future in a field, as the worked example does with late final, or create it in initState. After the fix, clear the table, repeat the action that caused the repeats, and confirm that one row appears.
Wrong or missing headers
A 401 or 403 status often means the token was missing, expired, or malformed. Open the Headers tab and check the request headers. A common mistake is a header name with a typo, or a token that is the string null because a variable was not yet loaded. The server's response body often names the reason, so read it before changing code.
Large or slow responses
Sort by Duration. Then ask which part of the time is the cost:
- A long wait before the first byte points at the server, or at a slow backend call behind it.
- A long download of a large body points at payload size. Check whether the server compresses it, whether you request more fields than the screen uses, and whether you should paginate.
- Many small sequential requests, each waiting for the previous one, point at a chain of awaits that could run in parallel with
Future.wait.
Images and caching
Images loaded with Image.network appear as rows of type image. If the same image downloads again each time a screen opens, look at the response headers. Missing Cache-Control or ETag headers mean the server gives the client no way to reuse the file. Flutter's image cache only holds decoded images in memory for the running session, so a cold start downloads them again unless you add a disk cache package.
Errors with no response
A request with no status usually failed before the server answered: a DNS failure, a refused connection, a TLS certificate problem, or a timeout. The row may show an error state, and the app usually throws a SocketException, a HandshakeException, or a TimeoutException. Combine the Network view with the Logging view. Catch the error and write it with developer.log so the exception message appears next to the failed row's timing.
import 'dart:developer' as developer;
import 'dart:io';
import 'package:http/http.dart' as http;
Future<String?> fetchText(Uri uri) async {
try {
final response = await http.get(uri).timeout(const Duration(seconds: 10));
return response.body;
} on SocketException catch (e, st) {
developer.log('Network unreachable', name: 'net', error: e, stackTrace: st);
} on HttpException catch (e, st) {
developer.log('HTTP problem', name: 'net', error: e, stackTrace: st);
}
return null;
}The timeout call throws a TimeoutException, which this function does not catch on purpose. Add a handler if you want to treat slow servers like other failures.
Where the view fits in a debugging session
The Network view answers one question first: did the problem happen before the request left the app, on the wire, or after the response arrived? The diagram shows how the answer routes you to another tool.
When the response is correct and the UI is still wrong, the fault is in your parsing or state code. Put a breakpoint after the call returns, or log the decoded values, as in earlier chapters.
Limits to remember
- Debug and profile mode only. In a release build, no VM service means no Network view.
- Large bodies may be truncated or slow to display in the details panes.
- Only
dart:iotraffic is visible. If one plugin's requests are missing, check whether it uses a native client. - Timing reflects the device you test on. A request on office Wi-Fi tells you little about a poor mobile connection. Test against a throttled network when latency matters.
Exercise
Your app's product list screen feels slow, and the Network view shows the same GET /products row 14 times after one scroll gesture, all with status 200. What is the most likely cause, where do you look in the code, and how do you confirm the fix in DevTools?
Show answer
Most likely a FutureBuilder (or similar) calls the fetch function inside build, so every rebuild during the scroll sends a new request. Look for a call such as future: fetchProducts() in a build method. Move the Future into a state field, created once in initState or with late final. To confirm, clear the Network table, repeat the same scroll gesture, and check that only one GET /products row appears.
Exercise
A login request returns status 401, but the credentials are correct. Name two things you can read in the Network view to find the cause, and one thing the view cannot do to help you test a fix.
Show answer
Read the request headers and request body to check that the fields and the Content-Type are what the server expects, and read the response body, which often states why the server refused the request. The Network view cannot edit and resend the request. It only records what happened, so you must change the code (or use a proxy tool) to try a modified request.