Skip to main content

flutter_auto_api_inspector 1.1.3 copy "flutter_auto_api_inspector: ^1.1.3" to clipboard
flutter_auto_api_inspector: ^1.1.3 copied to clipboard

Automatic network monitoring, screen-based API debugging, interactive JSON viewer, and in-app Debug Console for Flutter across Android, iOS, and Web.

example/lib/main.dart

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
// ignore: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:flutter_auto_api_inspector/flutter_auto_api_inspector.dart';
import 'package:http/http.dart' as http;

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // Step 1: Initialize once with full debug + console + screen tracking config.
  ApiInspector.initialize(
    config: const ApiInspectorConfig(
      enabled: true,
      showConsoleLogs: true,
      captureAppConsoleLogs: true,
      showRequest: true,
      showResponse: true,
      showHeaders: true,
      showRequestBody: true,
      showResponseBody: true,
      enableScreenTracking: true,
      enableDashboard: true,
      showFloatingButton: true,
      maxRequests: 500,
      slowRequestThreshold: Duration(milliseconds: 900),
      // Priority 2 automatic URL-to-Screen mapping for prefetched APIs:
      screenRules: <String, String>{
        '/api/profile': 'ProfileScreen',
      },
    ),
  );

  // Step 2: Optional console capture Zone so print() also appears in the
  // In-App Debug Console tab alongside IDE Debug Console.
  ApiInspector.runWithConsoleCapture(() {
    runApp(const DemoShopApp());
  });
}

/// Shared networking layer demonstrating Mode A (attachDio) + Mode B (attachHttp).
class DemoApiService {
  DemoApiService._() {
    dio = ApiInspector.createDio(
      BaseOptions(
        baseUrl: 'https://api.demoshop.dev',
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 5),
      ),
    );
    dio.httpClientAdapter = _SimulatedDioAdapter();

    httpClient = ApiInspector.attachHttp(_SimulatedHttpClient());
  }

  static final DemoApiService instance = DemoApiService._();

  late final Dio dio;
  late final http.Client httpClient;

  /// Optional real live request to JSONPlaceholder (requires internet).
  final Dio liveDio = ApiInspector.createDio(
    BaseOptions(baseUrl: 'https://jsonplaceholder.typicode.com'),
  );
}

class DemoShopApp extends StatelessWidget {
  const DemoShopApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Auto API Inspector Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: const Color(0xFF2563EB),
      ),
      // Step 3: Inject responsive floating button & In-App Dashboard.
      builder: ApiInspector.builder,
      // Step 4: Automatic screen tracking observer.
      navigatorObservers: <NavigatorObserver>[
        ApiInspector.navigatorObserver,
      ],
      initialRoute: '/home',
      routes: <String, WidgetBuilder>{
        '/home': (_) => const HomeScreen(),
        '/categories': (_) => const CategoriesScreen(),
        '/products': (_) => const ProductsScreen(),
        '/profile': (_) => const ProfileScreen(),
        '/orders': (_) => const OrdersScreen(),
      },
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _status = 'Tap any button below, then tap the floating "API" pill.';

  Future<void> _runHomeDashboardApis() async {
    setState(() => _status = 'Loading home feed + banners (Dio)...');
    // ignore: avoid_print
    print('HomeScreen: Loading home feed & featured banners');
    await Future.wait<void>(<Future<void>>[
      DemoApiService.instance.dio.get<dynamic>(
        '/api/home',
        queryParameters: <String, dynamic>{'locale': 'en', 'currency': 'USD'},
      ),
      DemoApiService.instance.dio.get<dynamic>('/api/categories'),
    ]);
    if (!mounted) return;
    setState(() => _status = 'Captured 2 GET requests under HomeScreen!');
  }

  Future<void> _runLivePublicApi() async {
    setState(() => _status = 'Calling live JSONPlaceholder API...');
    try {
      await DemoApiService.instance.liveDio.get<dynamic>('/posts/1');
      if (!mounted) return;
      setState(
          () => _status = 'Live API call succeeded! Open Inspector to view.');
    } catch (e) {
      if (!mounted) return;
      setState(() => _status = 'Live call failed (captured in Inspector): $e');
    }
  }

  void _emitConsoleLogs() {
    // ignore: avoid_print
    print('Standard print() captured in BOTH IDE & In-App Debug Console!');
    debugPrint('debugPrint() trace from HomeScreen');
    ApiInspector.log(
      'Custom warning from checkout banner check',
      level: ConsoleLogLevel.warning,
      tag: 'CHECKOUT',
    );
    setState(() => _status = 'Emitted 3 logs -> open Inspector > Console tab!');
  }

  Future<void> _prefetchProfileAndOrdersFromHome() async {
    setState(
      () => _status =
          'Prefetching Profile (URL rule) & Orders (per-request override) from HomeScreen...',
    );
    await Future.wait<void>(<Future<void>>[
      // Priority 2: Automatically routed to ProfileScreen via config.screenRules!
      DemoApiService.instance.dio.get<dynamic>('/api/profile'),
      // Priority 1: Explicitly routed to OrdersScreen via per-request override!
      DemoApiService.instance.dio.get<dynamic>(
        '/api/orders',
        options: ApiInspector.screenOptions('OrdersScreen'),
      ),
    ]);
    if (!mounted) return;
    setState(
      () => _status =
          'Prefetched 2 APIs! Open Inspector > Screens to see them under ProfileScreen & OrdersScreen with "Prefetched from HomeScreen" badge.',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('HomeScreen'),
        actions: <Widget>[
          IconButton(
            tooltip: 'Open Inspector',
            icon: const Icon(Icons.bug_report_outlined),
            onPressed: () => ApiInspector.openDashboard(),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          Card(
            child: Padding(
              padding: const EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  const Text(
                    'Flutter Auto API Inspector Demo',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
                  ),
                  const SizedBox(height: 6),
                  Text(_status),
                ],
              ),
            ),
          ),
          const SizedBox(height: 12),
          FilledButton.icon(
            onPressed: () => Navigator.pushNamed(context, '/categories'),
            icon: const Icon(Icons.category_outlined),
            label: const Text('Show Category Screen (Auto-Loads API Data)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonalIcon(
            onPressed: _runHomeDashboardApis,
            icon: const Icon(Icons.cloud_download_outlined),
            label: const Text('Fetch Home + Categories (Dio GET 200)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonalIcon(
            onPressed: _prefetchProfileAndOrdersFromHome,
            icon: const Icon(Icons.bolt),
            label:
                const Text('Prefetch Profile & Orders (Smart Screen Mapping)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton.icon(
            onPressed: _runLivePublicApi,
            icon: const Icon(Icons.public),
            label: const Text(
                'Call Live Public API (jsonplaceholder.typicode.com)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton.icon(
            onPressed: _emitConsoleLogs,
            icon: const Icon(Icons.terminal),
            label:
                const Text('Emit Console Logs (print + debugPrint + custom)'),
          ),
          const SizedBox(height: 20),
          const Text(
            'Navigate Screens (Auto Screen-Wise Grouping)',
            style: TextStyle(fontWeight: FontWeight.w700),
          ),
          const SizedBox(height: 8),
          _NavTile(
            title: 'CategoriesScreen',
            subtitle: 'Auto-loads categories from API on open & displays cards',
            icon: Icons.category_outlined,
            onTap: () => Navigator.pushNamed(context, '/categories'),
          ),
          _NavTile(
            title: 'ProductsScreen',
            subtitle: 'GET / POST products + JSON tree inspection',
            icon: Icons.shopping_bag_outlined,
            onTap: () => Navigator.pushNamed(context, '/products'),
          ),
          _NavTile(
            title: 'ProfileScreen',
            subtitle:
                'package:http PUT + Sensitive Token Masking + Multipart Upload',
            icon: Icons.person_outline,
            onTap: () => Navigator.pushNamed(context, '/profile'),
          ),
          _NavTile(
            title: 'OrdersScreen',
            subtitle: '401, 500, Slow API, Timeout & Mid-Request Navigation',
            icon: Icons.receipt_long_outlined,
            onTap: () => Navigator.pushNamed(context, '/orders'),
          ),
        ],
      ),
    );
  }
}

class CategoriesScreen extends StatefulWidget {
  const CategoriesScreen({super.key});

  @override
  State<CategoriesScreen> createState() => _CategoriesScreenState();
}

class _CategoriesScreenState extends State<CategoriesScreen> {
  bool _loading = true;
  String? _error;
  Map<String, dynamic>? _featuredBanner;
  List<Map<String, dynamic>> _categories = <Map<String, dynamic>>[];
  String? _selectedCategoryName;
  List<Map<String, dynamic>> _selectedCategoryItems = <Map<String, dynamic>>[];
  bool _loadingItems = false;

  @override
  void initState() {
    super.initState();
    // Automatically fetches data as soon as the user navigates to this screen.
    // ApiInspector automatically captures these calls under "CategoriesScreen".
    unawaited(_loadCategories());
  }

  Future<void> _loadCategories() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final responses =
          await Future.wait<Response<dynamic>>(<Future<Response<dynamic>>>[
        DemoApiService.instance.dio.get<dynamic>(
          '/api/categories/featured',
          queryParameters: <String, dynamic>{'active': true},
        ),
        DemoApiService.instance.dio.get<dynamic>(
          '/api/categories',
          queryParameters: <String, dynamic>{'includeCounts': true},
        ),
      ]);

      final featuredData = responses[0].data as Map<String, dynamic>;
      final categoriesData = responses[1].data as Map<String, dynamic>;
      final rawList =
          (categoriesData['categories'] as List<dynamic>? ?? <dynamic>[])
              .cast<Map<String, dynamic>>();

      if (!mounted) return;
      setState(() {
        _featuredBanner = featuredData['banner'] as Map<String, dynamic>?;
        _categories = rawList;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = 'Failed to load categories: $e';
        _loading = false;
      });
    }
  }

  Future<void> _loadCategoryItems(Map<String, dynamic> category) async {
    final id = category['id'];
    final name = category['name'] as String? ?? 'Category';
    setState(() {
      _selectedCategoryName = name;
      _loadingItems = true;
      _selectedCategoryItems = <Map<String, dynamic>>[];
    });
    try {
      final response = await DemoApiService.instance.dio.get<dynamic>(
        '/api/categories/$id/items',
      );
      final data = response.data as Map<String, dynamic>;
      final items = (data['items'] as List<dynamic>? ?? <dynamic>[])
          .cast<Map<String, dynamic>>();
      if (!mounted) return;
      setState(() {
        _selectedCategoryItems = items;
        _loadingItems = false;
      });
    } catch (_) {
      if (!mounted) return;
      setState(() => _loadingItems = false);
    }
  }

  IconData _categoryIcon(String? iconName) {
    switch (iconName) {
      case 'devices':
        return Icons.devices_outlined;
      case 'checkroom':
        return Icons.checkroom_outlined;
      case 'chair':
        return Icons.chair_outlined;
      case 'fitness':
        return Icons.fitness_center_outlined;
      default:
        return Icons.category_outlined;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CategoriesScreen'),
        actions: <Widget>[
          IconButton(
            tooltip: 'Reload categories',
            icon: const Icon(Icons.refresh),
            onPressed: _loadCategories,
          ),
        ],
      ),
      body: _loading
          ? const Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  CircularProgressIndicator(),
                  SizedBox(height: 12),
                  Text('Auto-loading categories from API...'),
                ],
              ),
            )
          : _error != null
              ? Center(child: Text(_error!))
              : RefreshIndicator(
                  onRefresh: _loadCategories,
                  child: ListView(
                    padding: const EdgeInsets.all(16),
                    children: <Widget>[
                      if (_featuredBanner != null)
                        Container(
                          padding: const EdgeInsets.all(16),
                          margin: const EdgeInsets.only(bottom: 16),
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              colors: <Color>[
                                Color(0xFF1D4ED8),
                                Color(0xFF4F46E5),
                              ],
                            ),
                            borderRadius: BorderRadius.circular(14),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                '${_featuredBanner!['badge'] ?? 'FEATURED'}',
                                style: const TextStyle(
                                  color: Colors.amberAccent,
                                  fontSize: 11,
                                  fontWeight: FontWeight.w700,
                                  letterSpacing: 1,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '${_featuredBanner!['title'] ?? ''}',
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '${_featuredBanner!['subtitle'] ?? ''}',
                                style: const TextStyle(
                                  color: Colors.white70,
                                  fontSize: 13,
                                ),
                              ),
                            ],
                          ),
                        ),
                      Text(
                        'Loaded ${_categories.length} Categories Automatically (tap any category to fetch items)',
                        style: const TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 13,
                        ),
                      ),
                      const SizedBox(height: 10),
                      ..._categories.map((cat) {
                        final isSelected = _selectedCategoryName == cat['name'];
                        return Card(
                          margin: const EdgeInsets.only(bottom: 10),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                            side: BorderSide(
                              color: isSelected
                                  ? Theme.of(context).colorScheme.primary
                                  : Colors.transparent,
                              width: 1.5,
                            ),
                          ),
                          child: ListTile(
                            leading: CircleAvatar(
                              child: Icon(
                                _categoryIcon(cat['icon'] as String?),
                              ),
                            ),
                            title: Text(
                              '${cat['name']}',
                              style:
                                  const TextStyle(fontWeight: FontWeight.w700),
                            ),
                            subtitle: Text('${cat['description']}'),
                            trailing: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: <Widget>[
                                Text(
                                  '${cat['productCount']} items',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 12,
                                  ),
                                ),
                                Text(
                                  '${cat['discount']}',
                                  style: const TextStyle(
                                    color: Colors.green,
                                    fontSize: 11,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ],
                            ),
                            onTap: () => _loadCategoryItems(cat),
                          ),
                        );
                      }),
                      if (_selectedCategoryName != null) ...<Widget>[
                        const SizedBox(height: 12),
                        Text(
                          'Items in $_selectedCategoryName',
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                        const SizedBox(height: 8),
                        if (_loadingItems)
                          const Padding(
                            padding: EdgeInsets.all(16),
                            child: Center(child: CircularProgressIndicator()),
                          )
                        else
                          ..._selectedCategoryItems.map(
                            (item) => Card(
                              child: ListTile(
                                title: Text('${item['name']}'),
                                subtitle: Text('SKU: ${item['sku']}'),
                                trailing: Text(
                                  '\$${item['price']}',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w700,
                                  ),
                                ),
                              ),
                            ),
                          ),
                      ],
                    ],
                  ),
                ),
    );
  }
}

class ProductsScreen extends StatefulWidget {
  const ProductsScreen({super.key});

  @override
  State<ProductsScreen> createState() => _ProductsScreenState();
}

class _ProductsScreenState extends State<ProductsScreen> {
  String _message = 'Trigger Dio product APIs on ProductsScreen.';

  Future<void> _fetchProducts() async {
    await DemoApiService.instance.dio.get<dynamic>(
      '/api/products',
      queryParameters: <String, dynamic>{
        'page': 1,
        'limit': 20,
        'sort': 'popular'
      },
    );
    if (mounted) {
      setState(() =>
          _message = 'GET /api/products (200) captured under ProductsScreen');
    }
  }

  Future<void> _createProduct() async {
    await DemoApiService.instance.dio.post<dynamic>(
      '/api/products',
      data: <String, dynamic>{
        'name': 'Mechanical Keyboard Pro',
        'price': 149.99,
        'inStock': true,
        'tags': <String>['hardware', 'wireless', 'rgb'],
        'metadata': <String, dynamic>{
          'sku': 'MK-2026-PRO',
          'warehouse': 'US-EAST-1',
        },
      },
    );
    if (mounted) {
      setState(() =>
          _message = 'POST /api/products (201) captured under ProductsScreen');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ProductsScreen')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          Text(_message),
          const SizedBox(height: 12),
          FilledButton(
            onPressed: _fetchProducts,
            child: const Text('GET /api/products (Nested JSON Response)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonal(
            onPressed: _createProduct,
            child: const Text('POST /api/products (JSON Request Body)'),
          ),
        ],
      ),
    );
  }
}

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  String _message =
      'Tests package:http, sensitive masking, and multipart upload.';

  Future<void> _loginWithSensitiveData() async {
    await DemoApiService.instance.dio.post<dynamic>(
      '/api/auth/login',
      options: Options(
        headers: <String, dynamic>{
          'Authorization': 'Bearer super_secret_jwt_token_999',
          'X-Api-Key': 'live_key_123456',
        },
      ),
      data: <String, dynamic>{
        'email': 'dev@example.com',
        'password': 'MyUltraSecretPassword!',
        'device': 'iOS Simulator',
      },
    );
    if (mounted) {
      setState(
        () => _message =
            'POST /api/auth/login captured — check Headers & Body to verify masking!',
      );
    }
  }

  Future<void> _updateProfileViaHttp() async {
    final uri = Uri.parse('https://api.demoshop.dev/api/profile/update');
    await DemoApiService.instance.httpClient.put(
      uri,
      headers: <String, String>{
        'Content-Type': 'application/json',
        'Authorization': 'Bearer hidden_http_token',
      },
      body: jsonEncode(<String, dynamic>{
        'displayName': 'Flutter Engineer',
        'role': 'Lead Mobile Developer',
      }),
    );
    if (mounted) {
      setState(() =>
          _message = 'PUT /api/profile/update via package:http captured!');
    }
  }

  Future<void> _uploadAvatarMultipart() async {
    final formData = FormData.fromMap(<String, dynamic>{
      'userId': 'usr_42',
      'caption': 'Profile avatar',
      'avatar': MultipartFile.fromBytes(
        Uint8List.fromList(List<int>.filled(2048, 65)),
        filename: 'avatar.png',
      ),
    });
    await DemoApiService.instance.dio.post<dynamic>(
      '/api/profile/avatar',
      data: formData,
    );
    if (mounted) {
      setState(() =>
          _message = 'Multipart upload metadata captured under ProfileScreen!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ProfileScreen')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          Text(_message),
          const SizedBox(height: 12),
          FilledButton(
            onPressed: _loginWithSensitiveData,
            child: const Text(
                'POST /api/auth/login (Tests Sensitive Data Masking)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonal(
            onPressed: _updateProfileViaHttp,
            child: const Text('PUT /api/profile/update (via package:http)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton(
            onPressed: _uploadAvatarMultipart,
            child: const Text('POST /api/profile/avatar (Multipart Upload)'),
          ),
        ],
      ),
    );
  }
}

class OrdersScreen extends StatefulWidget {
  const OrdersScreen({super.key});

  @override
  State<OrdersScreen> createState() => _OrdersScreenState();
}

class _OrdersScreenState extends State<OrdersScreen> {
  String _message =
      'Test error categorization, slow calls, and async navigation.';

  Future<void> _triggerCall(String path) async {
    try {
      await DemoApiService.instance.dio.get<dynamic>(path);
      if (mounted) setState(() => _message = 'Completed $path');
    } catch (e) {
      if (mounted) setState(() => _message = 'Captured error for $path');
    }
  }

  Future<void> _navigateDuringRequest() async {
    // Starts request on OrdersScreen, then navigates immediately to ProfileScreen.
    // The inspector MUST still bind this request to OrdersScreen!
    unawaited(
      DemoApiService.instance.dio.get<dynamic>('/api/orders/slow'),
    );
    await Navigator.pushNamed(context, '/profile');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('OrdersScreen')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          Text(_message),
          const SizedBox(height: 12),
          FilledButton(
            onPressed: () => _triggerCall('/api/orders'),
            child: const Text('GET /api/orders (200 OK)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonal(
            onPressed: () => _triggerCall('/api/orders/unauthorized'),
            child: const Text('GET /api/orders/unauthorized (401 Error)'),
          ),
          const SizedBox(height: 8),
          FilledButton.tonal(
            onPressed: () => _triggerCall('/api/orders/history'),
            child: const Text('GET /api/orders/history (500 Server Error)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton(
            onPressed: () => _triggerCall('/api/orders/slow'),
            child: const Text('GET /api/orders/slow (Slow API ~1.2s)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton(
            onPressed: () => _triggerCall('/api/orders/timeout'),
            child: const Text('GET /api/orders/timeout (Connection Timeout)'),
          ),
          const SizedBox(height: 8),
          OutlinedButton.icon(
            onPressed: _navigateDuringRequest,
            icon: const Icon(Icons.alt_route),
            label: const Text('Start Slow Request & Navigate to ProfileScreen'),
          ),
        ],
      ),
    );
  }
}

class _NavTile extends StatelessWidget {
  const _NavTile({
    required this.title,
    required this.subtitle,
    required this.icon,
    required this.onTap,
  });

  final String title;
  final String subtitle;
  final IconData icon;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Icon(icon),
        title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
        subtitle: Text(subtitle),
        trailing: const Icon(Icons.chevron_right),
        onTap: onTap,
      ),
    );
  }
}

/// Offline-friendly simulated Dio adapter so the demo runs reliably anywhere.
class _SimulatedDioAdapter implements HttpClientAdapter {
  @override
  Future<ResponseBody> fetch(
    RequestOptions options,
    Stream<Uint8List>? requestStream,
    Future<void>? cancelFuture,
  ) async {
    final path = options.path;

    if (path.contains('timeout')) {
      await Future<void>.delayed(const Duration(milliseconds: 350));
      throw DioException.connectionTimeout(
        timeout: const Duration(seconds: 5),
        requestOptions: options,
      );
    }

    if (path.contains('slow')) {
      await Future<void>.delayed(const Duration(milliseconds: 1200));
    } else {
      await Future<void>.delayed(const Duration(milliseconds: 160));
    }

    if (path.contains('unauthorized')) {
      return _jsonResponse(
        401,
        <String, dynamic>{
          'error': 'unauthorized',
          'message': 'Session expired. Please sign in again.',
        },
        statusMessage: 'Unauthorized',
      );
    }

    if (path.contains('history')) {
      return _jsonResponse(
        500,
        <String, dynamic>{
          'error': 'internal_server_error',
          'traceId': 'tr_901827',
          'message': 'Orders archive database timed out.',
        },
        statusMessage: 'Internal Server Error',
      );
    }

    if (path.contains('/auth/login')) {
      return _jsonResponse(
        200,
        <String, dynamic>{
          'user': <String, dynamic>{'id': 42, 'email': 'dev@example.com'},
          'access_token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.secret',
          'refresh_token': 'rt_999999_secret',
          'expiresIn': 3600,
        },
      );
    }

    if (path.contains('/categories/featured')) {
      return _jsonResponse(
        200,
        <String, dynamic>{
          'success': true,
          'banner': <String, dynamic>{
            'badge': 'AUTO-LOADED ON SCREEN OPEN',
            'title': 'Seasonal Tech & Lifestyle Sale',
            'subtitle':
                'Fetched automatically in CategoriesScreen.initState() — check the floating API pill!',
          },
        },
      );
    }

    if (RegExp(r'/categories/[^/]+/items').hasMatch(path)) {
      final categoryId = path.split('/')[3];
      return _jsonResponse(
        200,
        <String, dynamic>{
          'success': true,
          'categoryId': categoryId,
          'items': <Map<String, dynamic>>[
            <String, dynamic>{
              'id': '${categoryId}_1',
              'name': 'Premium $categoryId Essential',
              'sku': 'SKU-${categoryId.toUpperCase()}-101',
              'price': 89.99,
            },
            <String, dynamic>{
              'id': '${categoryId}_2',
              'name': 'Pro $categoryId Edition',
              'sku': 'SKU-${categoryId.toUpperCase()}-202',
              'price': 149.00,
            },
          ],
        },
      );
    }

    if (path.endsWith('/categories')) {
      return _jsonResponse(
        200,
        <String, dynamic>{
          'success': true,
          'count': 4,
          'categories': <Map<String, dynamic>>[
            <String, dynamic>{
              'id': 'electronics',
              'name': 'Electronics & Gadgets',
              'description': 'Laptops, headphones, monitors & accessories',
              'productCount': 128,
              'discount': 'Up to 25% OFF',
              'icon': 'devices',
            },
            <String, dynamic>{
              'id': 'fashion',
              'name': 'Fashion & Apparel',
              'description': 'Everyday wear, footwear & seasonal styles',
              'productCount': 245,
              'discount': 'Up to 40% OFF',
              'icon': 'checkroom',
            },
            <String, dynamic>{
              'id': 'home',
              'name': 'Home & Workspace',
              'description': 'Standing desks, ergonomic chairs & lighting',
              'productCount': 86,
              'discount': 'Up to 15% OFF',
              'icon': 'chair',
            },
            <String, dynamic>{
              'id': 'fitness',
              'name': 'Fitness & Wellness',
              'description': 'Smart wearables, recovery gear & hydration',
              'productCount': 64,
              'discount': 'Up to 20% OFF',
              'icon': 'fitness',
            },
          ],
        },
      );
    }

    if (path.contains('/products')) {
      if (options.method == 'POST') {
        return _jsonResponse(
          201,
          <String, dynamic>{
            'created': true,
            'id': 'prod_981',
            'received': options.data,
          },
          statusMessage: 'Created',
        );
      }
      return _jsonResponse(
        200,
        <String, dynamic>{
          'success': true,
          'count': 3,
          'items': <Map<String, dynamic>>[
            <String, dynamic>{
              'id': 1,
              'name': 'Noise Cancelling Headphones',
              'price': 299.0,
              'rating': 4.8,
            },
            <String, dynamic>{
              'id': 2,
              'name': 'Ergonomic Standing Desk',
              'price': 549.5,
              'rating': 4.9,
            },
            <String, dynamic>{
              'id': 3,
              'name': 'USB-C 4K Monitor',
              'price': 420.0,
              'rating': 4.7,
            },
          ],
        },
      );
    }

    return _jsonResponse(
      200,
      <String, dynamic>{
        'success': true,
        'endpoint': path,
        'method': options.method,
        'timestamp': DateTime.now().toIso8601String(),
      },
    );
  }

  ResponseBody _jsonResponse(
    int statusCode,
    Map<String, dynamic> payload, {
    String statusMessage = 'OK',
  }) {
    return ResponseBody.fromString(
      jsonEncode(payload),
      statusCode,
      statusMessage: statusMessage,
      headers: <String, List<String>>{
        Headers.contentTypeHeader: <String>['application/json; charset=utf-8'],
        'x-powered-by': <String>['DemoShopAPI'],
      },
    );
  }

  @override
  void close({bool force = false}) {}
}

/// Offline-friendly simulated `package:http` client for the Profile PUT demo.
class _SimulatedHttpClient extends http.BaseClient {
  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    await Future<void>.delayed(const Duration(milliseconds: 190));
    final bodyBytes = utf8.encode(
      jsonEncode(<String, dynamic>{
        'updated': true,
        'endpoint': request.url.path,
        'profile': <String, dynamic>{
          'displayName': 'Flutter Engineer',
          'verified': true,
        },
      }),
    );
    return http.StreamedResponse(
      Stream<List<int>>.value(bodyBytes),
      200,
      contentLength: bodyBytes.length,
      request: request,
      reasonPhrase: 'OK',
      headers: <String, String>{
        'content-type': 'application/json; charset=utf-8',
      },
    );
  }
}
0
likes
0
points
0
downloads

Publisher

unverified uploader

Weekly Downloads

Automatic network monitoring, screen-based API debugging, interactive JSON viewer, and in-app Debug Console for Flutter across Android, iOS, and Web.

Repository (GitHub)
View/report issues

Topics

#networking #debugging #inspector #dio #http

License

unknown (license)

Dependencies

dio, flutter, http

More

Packages that depend on flutter_auto_api_inspector