Skip to main content

hq_devtools 0.0.4 copy "hq_devtools: ^0.0.4" to clipboard
hq_devtools: ^0.0.4 copied to clipboard

A professional developer error widget and diagnostics tool for Flutter, offering crash reports, system logs, device info, and export capabilities out-of-the-box.

example/lib/main.dart

import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:hq_devtools/hq_devtools.dart';

void main() {
  // 1. Ensure Flutter bindings are initialized
  WidgetsFlutterBinding.ensureInitialized();

  // 2. Initialize HqDevTools configuration
  HqDevToolsConfig.init(
    HqDevToolsConfig(
      // True to show the bottom sheet, false to suppress it
      showDeveloperErrorDetails: true,

      // Display the minimal widget that expands on tap (default), or fullScreen
      displayMode: ErrorWidgetDisplayMode.minimal,

      // Optional callback to fetch logs from your app's logging system
      onLogsRequested: (from, to) async {
        // Simulated delay for reading logs
        await Future.delayed(const Duration(milliseconds: 500));
        return '[INFO] App Started\n[WARN] Network is slow\n[DEBUG] Example log entry...';
      },

      // Optional custom strings if you want to localize the package
      strings: const HqDevToolsStrings(
        title: 'App Crashed (Dev Mode)',
        tapForDetails: 'Tap here to see crash details',
      ),
    ),
  );

  // 3. Catch Flutter framework errors
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.presentError(details);
    debugPrint('Flutter Error Caught: ${details.exceptionAsString()}');
  };

  // 4. Override ErrorWidget to show DeveloperErrorWidget on UI crashes
  ErrorWidget.builder = (FlutterErrorDetails details) {
    debugPrint('Widget Build Error Caught: ${details.exceptionAsString()}');
    return DeveloperErrorWidget(details: details);
  };

  // 5. Catch Dart asynchronous errors (Platform exceptions)
  PlatformDispatcher.instance.onError = (Object error, StackTrace stackTrace) {
    debugPrint('Platform Error Caught: $error');
    // We can't show a widget here directly, but we could trigger a navigation
    // or log it. The UI errors will be caught by ErrorWidget.builder.
    return true; // Return true to indicate the error was handled
  };

  runApp(const DevToolsExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HqDevTools Example',
      navigatorObservers: [HqDevToolsRouteObserver()],
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const ExampleHomePage(),
    );
  }
}

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

  @override
  State<ExampleHomePage> createState() => _ExampleHomePageState();
}

class _ExampleHomePageState extends State<ExampleHomePage> {
  bool _causeRenderError = false;

  void _triggerFormatException() {
    try {
      int.parse('Not a number');
    } catch (e, stack) {
      // Simulate catching an error and showing the sheet manually
      final details = FlutterErrorDetails(
        exception: e,
        stack: stack,
        library: 'Manual Exception Trigger',
        context: ErrorDescription('Trying to parse invalid string'),
      );
      HqDevTools.showErrorSheet(context, details: details);
    }
  }

  void _triggerSocketException() {
    try {
      throw const SocketException('Failed host lookup: google.com');
    } catch (e, stack) {
      final details = FlutterErrorDetails(
        exception: e,
        stack: stack,
        library: 'Network Request',
        context: ErrorDescription('Fetching data from API'),
      );
      HqDevTools.showErrorSheet(context, details: details);
    }
  }

  void _triggerStateError() {
    try {
      final list = <int>[];
      list.first; // Throws StateError
    } catch (e, stack) {
      final details = FlutterErrorDetails(
        exception: e,
        stack: stack,
        library: 'List Operations',
        context: ErrorDescription('Accessing empty list'),
      );
      HqDevTools.showErrorSheet(context, details: details);
    }
  }

  @override
  Widget build(BuildContext context) {
    // 6. Demonstrate a UI Render Error
    if (_causeRenderError) {
      return Builder(
        builder: (context) {
          // This will throw a layout exception because it's impossible to size
          return SizedBox(
            height: double.infinity,
            child: Column(
              children: [Expanded(child: Container(color: Colors.red))],
            ),
          );
        },
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('HqDevTools Example'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                'Test different types of Developer Errors:',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 32),

              ElevatedButton.icon(
                onPressed: _triggerFormatException,
                icon: const Icon(Icons.text_format),
                label: const Text('Trigger FormatException'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
              const SizedBox(height: 16),

              ElevatedButton.icon(
                onPressed: _triggerSocketException,
                icon: const Icon(Icons.wifi_off),
                label: const Text('Trigger SocketException'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
              const SizedBox(height: 16),

              ElevatedButton.icon(
                onPressed: _triggerStateError,
                icon: const Icon(Icons.error_outline),
                label: const Text('Trigger StateError'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
              const SizedBox(height: 16),

              FilledButton.icon(
                onPressed: () {
                  setState(() {
                    _causeRenderError = true;
                  });
                },
                icon: const Icon(Icons.broken_image),
                label: const Text('Trigger UI Render Error'),
                style: FilledButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.error,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),

              const SizedBox(height: 32),
              const Text(
                'Note: UI Render errors will replace the screen with DeveloperErrorWidget. Tap it to view details.',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
0
likes
140
points
23
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A professional developer error widget and diagnostics tool for Flutter, offering crash reports, system logs, device info, and export capabilities out-of-the-box.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

device_info_plus, flutter, package_info_plus, path_provider, share_plus, uuid

More

Packages that depend on hq_devtools