Developer

Chandhuru Varatharaj

Flutter Developer | Open Source Contributor

GitHub: https://github.com/chandhur

flutter_api_traffic_inspector

pub package License: MIT

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.


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 Dart http.Client (ApiInspectorHttpClient).
  • 🔌 WebSocket Inspector: Wrap web_socket_channel with InspectedWebSocketChannel to see connection state and every sent/received message in a chat-style view.
  • 🔒 Security First: Automatically masks sensitive headers (Authorization, Cookie, X-API-Key) and body/query fields (password, token, secret) before storage or display.
  • 💾 SQLite Persistent History: Stores transactions across app restarts with automatic capacity limits (default: 500 records) and pagination.
  • 🔍 Real-Time Search & Filtering: Filter by HTTP Method (GET, POST, PUT, DELETE, PATCH), Status Codes (2xx, 4xx, 5xx, Network Errors), Date Range, and URL query text.
  • 📋 Developer Tools:
    • Pretty-printed JSON viewer with in-viewer search and keyword highlighting.
    • One-click Copy as cURL command generation.
    • Complete JSON transaction export.
    • 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: Easily bypass completely in release builds with enabled: kDebugMode. 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.2.0

Then run:

flutter pub get

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 (kept in memory only).


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, all inspection and overlays are completely bypassed.
showFloatingButton bool true Controls whether the draggable floating debug button is rendered.
enablePersistentHistory bool true Persists API transaction history to an embedded SQLite database.
maxHistoryEntries int 500 Maximum number of records retained in storage before older entries are pruned.
themeMode InspectorThemeMode system Default theme: light, dark, or system.
sensitiveHeaders List<String> ['authorization', 'cookie', 'set-cookie', 'x-api-key'] Headers whose values will be masked as ********.
sensitiveFields List<String> ['password', 'access_token', 'refresh_token', 'token', 'secret'] Body keys and query parameters whose values will be masked.

Security & Reliability Design

  • Masking at the Source: Sensitive data is masked before being passed to storage or UI rendering. Original tokens never exist in SQLite or the dashboard.
  • Fail-Safe Networking: All inspection handlers run inside protected error boundaries. If the inspector throws an error, the underlying HTTP request or response will continue without interruption.
  • Stream Preservation: Streamed responses and large binary files (images, audio, videos, PDFs) are never consumed prematurely or stored as raw byte arrays.
  • Payload Truncation: Strings exceeding 10,000 characters are automatically truncated in the inspector store to maintain smooth 60fps UI rendering.

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.