HTTP Network Request Logging with HTTP Library in FLutter

Logging network request in flutter app.

Sample App.

http: ^0.13.4
import 'package:flutter/material.dart';
import 'api.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
final api = Api();
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Http Logger Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: EdgeInsets.all(16),
width: double.infinity,
child: ElevatedButton(
onPressed: api.mockGet,
child: Text('GET'),
style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor,
padding: EdgeInsets.all(16),
),
),
),
Container(
margin: EdgeInsets.all(16),
width: double.infinity,
child: ElevatedButton(
onPressed: api.mockPost,
child: Text('POST'),
style: ElevatedButton.styleFrom(
primary: Theme.of(context).errorColor,
padding: EdgeInsets.all(16),
),
),
),
],
),
),
),
);
}
}
import 'dart:convert';
import 'package:http/http.dart';

class Api {
final _client = Client();

Future<void> mockGet() async {
final url = Uri.parse("https://jsonplaceholder.typicode.com/posts/1");
try {
final response = await _client.get(url);
final body = jsonDecode(response.body);
print("Request url: ${response.request?.url}");
print("Request headers: ${response.request?.headers}");
print("Response header: ${response.headers}");
print("Response body: ${response.body}");
return body;
} catch (e) {
print("Response exception: $e");
throw Exception("$e".replaceAll("Exception:", ""));
}
}

Future<void> mockPost() async {
final url = Uri.parse("https://jsonplaceholder.typicode.com/posts/");
try {
final response =
await _client.post(url, body: jsonEncode({"username": "123"}));
final body = jsonDecode(response.body);
print("Request url: ${response.request?.url}");
print("Request headers: ${response.request?.headers}");
print("Response header: ${response.headers}");
print("Response body: ${response.body}");
return body;
} catch (e) {
print("Response exception: $e");
throw Exception("$e".replaceAll("Exception:", ""));
}
}
}
Logging network request in flutter app.
pretty_http_logger: ^0.2.1
HttpClientWithMiddleware _client = HttpClientWithMiddleware.build(middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
]);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store