flutter_api_traffic_inspector 0.3.0
flutter_api_traffic_inspector: ^0.3.0 copied to clipboard
A developer-friendly HTTP and WebSocket traffic inspector for Flutter with a real-time tabbed UI, Dio & http support, and SQLite persistence.
flutter_api_traffic_inspector #
A modern, developer-friendly in-app HTTP & WebSocket Inspector for Flutter applications. Inspect network traffic, view formatted JSON payloads, mask sensitive credentials, export cURL commands, and persist request history with SQLite β all without tethering to a computer or proxy.
Developer: Chandhuru Varatharaj β Flutter Developer | Open Source Contributor Β· GitHub
Features #
- π Zero Configuration Floating Debug Button: Drag anywhere on the screen, displays real-time request counts and red error indicators.
- π‘ Universal Client Support: Drop-in adapters for both Dio (
ApiInspectorDioInterceptor) and standard Darthttp.Client(ApiInspectorHttpClient). - π WebSocket Inspector: Wrap
web_socket_channelwithInspectedWebSocketChannelto see connection state and every sent/received message in a chat-style view. History is persisted too. - π Security First: Masks sensitive headers, body fields (JSON, form-encoded and JSON-in-string), URL query values and WebSocket payloads/URLs before storage or display.
- πΎ SQLite Persistent History: Stores HTTP and WebSocket history across app restarts with automatic capacity limits (default: 500 records).
- βΎοΈ Pagination: The dashboard loads 50 rows at a time and fetches more as you scroll; the summary tiles use database aggregates, so they cover the whole history.
- π Real-Time Search & Filtering: Filter by HTTP Method, Status Codes (2xx, 4xx, 5xx, Network Errors), Date Range, and URL/method text (debounced).
- π Developer Tools:
- Pretty-printed JSON viewer with in-viewer search and keyword highlighting.
- Shell-safe Copy as cURL (includes the query string).
- Replay a captured request (long-press a row, or the toolbar button in the details screen). The replay is recorded as a new call.
- Delete a single call (long-press a row).
- Export the (filtered) list as JSON or HAR 1.2 from the dashboard's share menu.
- Live details: a pending request fills in when its response arrives.
- Key-value tables for headers and query parameters with per-item copy actions.
- π Light, Dark & System Themes: Material 3 responsive UI with custom status and method badge coloring.
- π‘οΈ Production Safe: With
enabled: kDebugModethe inspector records nothing and opens no database in release builds. Inspector failures never block actual network requests.
Getting Started #
Add flutter_api_traffic_inspector to your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
flutter_api_traffic_inspector: ^0.3.0
Requires Flutter 3.27 or newer.
Then run:
flutter pub get
Platforms: history persistence uses
sqflite, which supports Android, iOS and macOS out of the box. On Windows, Linux or web the database cannot open and the inspector falls back to in-memory storage (a message is printed in debug mode). To get persistence on desktop, set upsqflite_common_ffiand assigndatabaseFactorybeforeApiInspector.initialize.
Step-by-Step Setup #
1. Initialize in main.dart #
Initialize the inspector inside your main() before calling runApp(). Use kDebugMode to ensure the inspector is active only during development:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_api_traffic_inspector/flutter_api_traffic_inspector.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ApiInspector.initialize(
config: const InspectorConfig(
enabled: kDebugMode, // Disabled automatically in release builds
showFloatingButton: true,
enablePersistentHistory: true,
maxHistoryEntries: 500,
),
);
runApp(const MyApp());
}
2. Add the Floating Debug Button Overlay #
Wrap your MaterialApp with ApiInspectorOverlay inside builder:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Application',
// Injects the draggable floating inspector button
builder: (context, child) => ApiInspectorOverlay(
child: child!,
),
home: const HomeScreen(),
);
}
}
3. Attach to Your HTTP Client #
With Dio
Add ApiInspectorDioInterceptor() to your Dio interceptors list:
import 'package:dio/dio.dart';
import 'package:flutter_api_traffic_inspector/flutter_api_traffic_inspector.dart';
final dio = Dio(
BaseOptions(baseUrl: 'https://api.example.com'),
);
// Add the inspector interceptor
dio.interceptors.add(ApiInspectorDioInterceptor());
With Dart http.Client
Wrap your standard client with ApiInspectorHttpClient:
import 'package:http/http.dart' as http;
import 'package:flutter_api_traffic_inspector/flutter_api_traffic_inspector.dart';
final client = ApiInspectorHttpClient(
inner: http.Client(),
);
// Use exactly like standard http.Client
final response = await client.get(
Uri.parse('https://api.example.com/users'),
);
With WebSocket (web_socket_channel)
Replace WebSocketChannel.connect with InspectedWebSocketChannel.connect:
import 'package:flutter_api_traffic_inspector/flutter_api_traffic_inspector.dart';
final channel = InspectedWebSocketChannel.connect(
Uri.parse('wss://echo.websocket.org'),
);
channel.stream.listen(print);
channel.sink.add('hello');
channel.sink.close(1000, 'bye');
Or wrap an existing channel:
final wrapped = InspectedWebSocketChannel(existingChannel, url: 'wss://example.com');
Sessions appear in the WebSocket tab of the dashboard. Messages are recorded even if you start listening to channel.stream late, URLs/payloads are masked like HTTP traffic, and with persistence enabled sessions survive app restarts (a session that was live when the app stopped is shown as closed).
4. Programmatic Navigation (Optional) #
In addition to tapping the floating bubble, you can open the inspector dashboard programmatically anytime from any widget:
ElevatedButton(
onPressed: () => ApiInspector.open(context),
child: const Text('Open API Inspector'),
);
Configuration Reference (InspectorConfig) #
| Property | Type | Default | Description |
|---|---|---|---|
enabled |
bool |
true |
Master switch. When false, nothing is captured, no database is opened, and the overlay is not rendered. |
showFloatingButton |
bool |
true |
Controls whether the draggable floating debug button is rendered. |
enablePersistentHistory |
bool |
true |
Persists HTTP and WebSocket history to an embedded SQLite database. |
maxHistoryEntries |
int |
500 |
Maximum number of HTTP records kept, in memory and in storage; older entries are pruned. |
themeMode |
InspectorThemeMode |
system |
Default theme: light, dark, or system. |
sensitiveHeaders |
List<String> |
see InspectorConfig.defaultSensitiveHeaders |
Header names whose values are masked (case-insensitive). |
sensitiveFields |
List<String> |
see InspectorConfig.defaultSensitiveFields |
Body/query field names masked (case-insensitive, -/_ ignored). |
maxBodyChars |
int |
10000 |
Longest string stored for a request/response body. |
maxCapturedBodyBytes |
int |
1048576 |
Largest part of an http response body kept for display (the caller always gets the full body). |
maxWebSocketPayloadChars |
int |
10000 |
Longest WebSocket payload stored per message. |
The lists you pass replace the defaults. Names that clearly carry credentials (anything containing password, secret, token, authorization, apikey, cookie, β¦) are masked regardless.
Security & Reliability Design #
- Masking at the Source: Sensitive values are masked before they reach the in-memory store, SQLite or the UI, so the originals are never kept by the inspector. Masking covers headers, JSON bodies, JSON text, form-encoded text, URL query values, URL user-info, and WebSocket payloads. Masking is key-based: a secret that appears as a value under an innocuous key (or in free text) is not detected, so treat stored history as sensitive and keep the inspector out of production builds.
- Fail-Safe Networking: All inspection code runs inside protected error boundaries. If the inspector throws, the underlying HTTP request or response continues without interruption.
- Streaming Preserved: The
httpadapter forwards response chunks to your code as they arrive and keeps only a bounded copy for display. Binary content (images, audio, video, PDFs) is summarised, never stored. DioResponseType.streambodies are not captured. - Multipart/streamed requests: only a placeholder is recorded; their bodies are not read.
- Bounded Memory: In-memory HTTP records are capped at
maxHistoryEntries; WebSocket history is capped at 50 sessions Γ 1000 messages; long strings and arrays are truncated (with a visible marker). - Late initialization is safe: adapters resolve the global inspector on every call, so creating a
Dio/ApiInspectorHttpClientbeforeApiInspector.initializestill records into the configured inspector. - Replay caveat: stored requests are masked, so masked headers/query values are left out when replaying (the UI tells you how many); masked values inside a body are sent as
********.
Example App #
Check out the example/ directory for a complete Flutter app utilizing the DummyJSON Products API with BLoC/Cubit state management, 2-column GridView, infinite scroll pagination, and dynamic details inspection.
cd example
flutter run
License #
This project is licensed under the MIT License - see the LICENSE file for details.