### Installation and Basic Setup Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Instructions on how to add the Flutter Performance Pulse package to your project and a basic example of initializing the performance monitor and integrating the dashboard into your Flutter application. ```APIDOC ## Installation Add Flutter Pulse to your pubspec.yaml: ```yaml dependencies: flutter_performance_pulse: ^1.0.6 ``` ## Basic Setup This example demonstrates how to initialize the `PerformanceMonitor` and integrate the `PerformanceDashboard` into your Flutter app. ### Code Example ```dart import 'package:flutter/material.dart'; import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize with default configuration await PerformanceMonitor.instance.initialize(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), builder: (context, child) { return Stack( children: [ child!, const Positioned( right: 16, bottom: 16, child: Material( elevation: 8, borderRadius: BorderRadius.all(Radius.circular(8)), child: PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, // Enable disk monitoring theme: DashboardTheme( backgroundColor: Color(0xFF1E1E1E), textColor: Colors.white, warningColor: Colors.orange, errorColor: Colors.red, chartLineColor: Colors.blue, chartFillColor: Color(0x40808080), ), ), ), ), ], ); }, home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter Performance Pulse Demo'), ), body: const Center( child: Text('Your app content here'), ), ); } } ``` ### Explanation 1. **Import necessary packages**: `flutter/material.dart` and `flutter_performance_pulse/flutter_performance_pulse.dart`. 2. **Initialize Monitor**: Call `PerformanceMonitor.instance.initialize()` in your `main` function after `WidgetsFlutterBinding.ensureInitialized()` to set up the performance monitoring. 3. **Integrate Dashboard**: Use the `builder` property of `MaterialApp` to wrap your app. A `Stack` is used to overlay the `PerformanceDashboard` on top of your app's content. The dashboard is positioned at the bottom right corner. 4. **Dashboard Configuration**: The `PerformanceDashboard` widget accepts several parameters: * `showFPS`: Boolean to show/hide Frames Per Second. * `showCPU`: Boolean to show/hide CPU usage. * `showDisk`: Boolean to show/hide Disk I/O monitoring. * `theme`: Allows customization of the dashboard's appearance with `DashboardTheme`. ``` -------------------------------- ### Disk Monitoring Example Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Provides an example of enabling disk monitoring, adding it to the dashboard, and testing disk operations. ```APIDOC ## Disk Monitoring Example ### Description Provides an example of enabling disk monitoring, adding it to the dashboard, and testing disk operations. ### Initialization ```dart // Initialize with disk monitoring await PerformanceMonitor.instance.initialize( config: MonitorConfig( enableDiskMonitoring: true, diskWarningThreshold: 85.0, // Show warning when disk usage exceeds 85% ), ); ``` ### Dashboard Integration ```dart PerformanceDashboard( showDisk: true, theme: DashboardTheme.dark(), ) ``` ### Testing Disk Operations ```dart Future testDiskOperations() async { final appDir = await getApplicationDocumentsDirectory(); final testFile = File('${appDir.path}/test_file.txt'); // Write test data await testFile.writeAsString('Test data'); // Get file stats final fileStats = await testFile.stat(); print('File size: ${fileStats.size} bytes'); // Clean up await testFile.delete(); } ``` ``` -------------------------------- ### GET /deviceStream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Retrieves comprehensive device hardware and OS information. ```APIDOC ## GET /deviceStream ### Description Retrieves detailed device specifications including model, OS, and manufacturer. This is a one-time emission upon subscription. ### Method GET (Stream) ### Endpoint PerformanceMonitor.instance.deviceStream ### Response #### Success Response (200) - **model** (string) - The device model name - **os** (string) - The operating system name (e.g., Android, iOS) - **osVersion** (string) - The OS version string - **manufacturer** (string) - The device manufacturer #### Response Example { "model": "Pixel 6", "os": "Android", "osVersion": "13", "manufacturer": "Google" } ``` -------------------------------- ### Initialize Performance Monitor Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Configures and starts the performance tracking singleton. This should be called during app startup to define thresholds and enable specific monitoring features. ```dart import 'package:flutter/material.dart'; import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await PerformanceMonitor.instance.initialize( config: const MonitorConfig( showMemory: true, showLogs: true, trackStartup: true, interceptNetwork: true, fpsWarningThreshold: 45, memoryWarningThreshold: 500 * 1024 * 1024, diskWarningThreshold: 85.0, enableNetworkMonitoring: true, enableBatteryMonitoring: true, enableDeviceInfo: true, enableDiskMonitoring: true, logLevel: LogLevel.info, exportLogs: false, ), ); runApp(const MyApp()); } ``` -------------------------------- ### GET /diskStream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Subscribes to the disk stream to monitor storage metrics including total, free, and used space. ```APIDOC ## GET diskStream ### Description Provides a stream of DiskData objects updated every 5 seconds, offering insights into device storage capacity and usage percentages. ### Method GET (Stream Subscription) ### Endpoint PerformanceMonitor.instance.diskStream ### Response #### Success Response (Stream Event) - **usagePercentage** (double) - Calculated percentage of disk space used. - **freeSpace** (int) - Available free space in bytes. - **totalSpace** (int) - Total disk capacity in bytes. - **usedSpace** (int) - Total used space in bytes. - **appStorage** (int) - Storage space consumed by the application. ### Response Example { "usagePercentage": 45.5, "freeSpace": 53687091200, "totalSpace": 128849018880, "usedSpace": 58642432000, "appStorage": 104857600 } ``` -------------------------------- ### GET /batteryStream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Subscribes to real-time battery status updates including level and charging state. ```APIDOC ## GET /batteryStream ### Description Subscribes to the battery stream to receive continuous updates on the device's battery level and charging state. ### Method GET (Stream) ### Endpoint PerformanceMonitor.instance.batteryStream ### Response #### Success Response (200) - **level** (int) - Battery percentage (0-100) - **isCharging** (bool) - Convenience flag for charging status - **state** (BatteryState) - Enum representing the current battery state (charging, discharging, full, etc.) #### Response Example { "level": 85, "isCharging": true, "state": "charging" } ``` -------------------------------- ### GET /memoryStream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Subscribes to the memory stream to receive real-time updates on heap usage and garbage collection events. ```APIDOC ## GET memoryStream ### Description Provides a stream of MemoryData objects updated every second, containing heap usage statistics and GC status. ### Method GET (Stream Subscription) ### Endpoint PerformanceMonitor.instance.memoryStream ### Response #### Success Response (Stream Event) - **heapUsage** (int) - Current heap memory usage in bytes. - **hadGC** (bool) - Indicates if a garbage collection event occurred since the last update. ### Response Example { "heapUsage": 15728640, "hadGC": false } ``` -------------------------------- ### Initialize and Configure Performance Monitor Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Demonstrates how to initialize the PerformanceMonitor in the main function and integrate the PerformanceDashboard widget into the app's builder to display real-time metrics. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize with default configuration await PerformanceMonitor.instance.initialize(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'My App', builder: (context, child) { return Stack( children: [ child!, const Positioned( right: 16, bottom: 16, child: Material( elevation: 8, borderRadius: BorderRadius.all(Radius.circular(8)), child: PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme( backgroundColor: Color(0xFF1E1E1E), textColor: Colors.white, warningColor: Colors.orange, errorColor: Colors.red, chartLineColor: Colors.blue, chartFillColor: Color(0x40808080), ), ), ), ), ], ); }, home: const MyHomePage(), ); } } ``` -------------------------------- ### Implement Disk Monitoring Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Shows how to enable disk monitoring in the configuration and perform basic file operations to test the monitoring capabilities. ```dart await PerformanceMonitor.instance.initialize( config: MonitorConfig( enableDiskMonitoring: true, diskWarningThreshold: 85.0, ), ); Future testDiskOperations() async { final appDir = await getApplicationDocumentsDirectory(); final testFile = File('${appDir.path}/test_file.txt'); await testFile.writeAsString('Test data'); final fileStats = await testFile.stat(); print('File size: ${fileStats.size} bytes'); await testFile.delete(); } ``` -------------------------------- ### Configure PerformanceMonitor with MonitorConfig Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Demonstrates how to initialize and customize the performance monitoring settings using the MonitorConfig class. It shows creating a full configuration, using copyWith for modifications, and accessing the current instance configuration. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; const defaultConfig = MonitorConfig(); const fullConfig = MonitorConfig( showMemory: true, showLogs: true, trackStartup: true, interceptNetwork: true, enableNetworkMonitoring: true, enableBatteryMonitoring: true, enableDeviceInfo: true, enableDiskMonitoring: true, fpsWarningThreshold: 45, memoryWarningThreshold: 500 * 1024 * 1024, diskWarningThreshold: 90.0, logLevel: LogLevel.info, exportLogs: false, ); final customConfig = fullConfig.copyWith( fpsWarningThreshold: 30, diskWarningThreshold: 80.0, logLevel: LogLevel.debug, ); final currentConfig = PerformanceMonitor.instance.config; print('FPS threshold: ${currentConfig.fpsWarningThreshold}'); ``` -------------------------------- ### Initialize Performance Monitor with Advanced Configuration Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Initializes the Performance Monitor with detailed configuration options including performance thresholds, feature toggles, and logging settings. ```APIDOC ## Initialize Performance Monitor with Advanced Configuration ### Description Initializes the Performance Monitor with detailed configuration options including performance thresholds, feature toggles, and logging settings. ### Method `await PerformanceMonitor.instance.initialize()` ### Parameters #### Request Body - **config** (MonitorConfig) - Required - Configuration object for the performance monitor. - **showMemory** (bool) - Optional - Enables memory usage tracking. - **showLogs** (bool) - Optional - Enables general logging. - **trackStartup** (bool) - Optional - Enables tracking of application startup time. - **interceptNetwork** (bool) - Optional - Enables network request interception. - **fpsWarningThreshold** (int) - Optional - The FPS threshold to trigger a warning. - **memoryWarningThreshold** (int) - Optional - The memory usage threshold (in bytes) to trigger a warning. - **diskWarningThreshold** (double) - Optional - The disk usage percentage threshold to trigger a warning. - **enableNetworkMonitoring** (bool) - Optional - Enables network monitoring features. - **enableBatteryMonitoring** (bool) - Optional - Enables battery status monitoring. - **enableDeviceInfo** (bool) - Optional - Enables collection of device information. - **enableDiskMonitoring** (bool) - Optional - Enables disk usage monitoring. - **logLevel** (LogLevel) - Optional - Sets the verbosity level for logs. - **exportLogs** (bool) - Optional - Enables exporting of logs. ### Request Example ```dart await PerformanceMonitor.instance.initialize( config: MonitorConfig( showMemory: true, showLogs: true, trackStartup: true, interceptNetwork: true, fpsWarningThreshold: 45, memoryWarningThreshold: 500 * 1024 * 1024, // 500MB diskWarningThreshold: 85.0, // Warn at 85% disk usage enableNetworkMonitoring: true, enableBatteryMonitoring: true, enableDeviceInfo: true, enableDiskMonitoring: true, logLevel: LogLevel.verbose, exportLogs: true, ), ); ``` ``` -------------------------------- ### Initialize Performance Monitor Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Configures the global performance monitoring settings including thresholds for memory, disk, and FPS, as well as feature toggles for various system metrics. ```dart await PerformanceMonitor.instance.initialize( config: MonitorConfig( showMemory: true, showLogs: true, trackStartup: true, interceptNetwork: true, fpsWarningThreshold: 45, memoryWarningThreshold: 500 * 1024 * 1024, diskWarningThreshold: 85.0, enableNetworkMonitoring: true, enableBatteryMonitoring: true, enableDeviceInfo: true, enableDiskMonitoring: true, logLevel: LogLevel.verbose, exportLogs: true, ), ); ``` -------------------------------- ### Performance Dashboard Customization Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Demonstrates how to create and customize the Performance Dashboard, including setting up themes and enabling specific metrics. ```APIDOC ## Performance Dashboard Customization ### Description Demonstrates how to create and customize the Performance Dashboard, including setting up themes and enabling specific metrics. ### Parameters #### Request Body - **showFPS** (bool) - Optional - Whether to display FPS information. - **showCPU** (bool) - Optional - Whether to display CPU usage information. - **showDisk** (bool) - Optional - Whether to display disk usage information. - **theme** (DashboardTheme) - Optional - The theme to apply to the dashboard. - **backgroundColor** (Color) - Optional - Background color of the dashboard. - **textColor** (Color) - Optional - Text color for dashboard elements. - **warningColor** (Color) - Optional - Color for warning indicators. - **errorColor** (Color) - Optional - Color for error indicators. - **chartLineColor** (Color) - Optional - Color for chart lines. - **chartFillColor** (Color) - Optional - Color for chart fill areas. ### Request Example (Custom Theme) ```dart PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme( backgroundColor: Colors.black87, textColor: Colors.white, warningColor: Colors.amber, errorColor: Colors.redAccent, chartLineColor: Colors.greenAccent, chartFillColor: Colors.greenAccent.withOpacity(0.2), ), ) ``` ### Request Example (Light Theme) ```dart PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme.light(), ) ``` ### Request Example (Dark Theme) ```dart PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme.dark(), ) ``` ``` -------------------------------- ### Customize Dashboard Appearance with DashboardTheme Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Demonstrates how to apply built-in light and dark themes, create custom theme configurations, and modify existing themes using the copyWith method for the PerformanceDashboard widget. ```dart import 'package:flutter/material.dart'; import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; // Use built-in dark theme const darkDashboard = PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme.dark(), ); // Use built-in light theme const lightDashboard = PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme.light(), ); // Create custom theme final customTheme = DashboardTheme( backgroundColor: Colors.black87, textColor: Colors.white, warningColor: Colors.amber, errorColor: Colors.redAccent, chartLineColor: Colors.greenAccent, chartFillColor: Colors.greenAccent.withOpacity(0.2), ); // Modify existing theme with copyWith final modifiedTheme = DashboardTheme.dark().copyWith( chartLineColor: Colors.purple, warningColor: Colors.yellow, ); ``` -------------------------------- ### Monitor Processor Usage with CPU Stream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Illustrates how to consume the cpuStream to retrieve CPU usage percentage and core count. The data is used to drive a dynamic UI component, such as a LinearProgressIndicator, to visualize system load. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class CpuMonitorWidget extends StatefulWidget { @override State createState() => _CpuMonitorWidgetState(); } class _CpuMonitorWidgetState extends State { double _cpuUsage = 0.0; int _cores = 0; @override void initState() { super.initState(); // Subscribe to CPU updates (updated every second) PerformanceMonitor.instance.cpuStream.listen((CpuData data) { setState(() { _cpuUsage = data.usage; // Percentage 0-100 _cores = data.cores; // Number of CPU cores }); }); } @override Widget build(BuildContext context) { return Column( children: [ Text('CPU: ${_cpuUsage.toStringAsFixed(1)}%'), Text('Cores: $_cores'), LinearProgressIndicator( value: _cpuUsage / 100, backgroundColor: Colors.grey[300], color: _cpuUsage > 80 ? Colors.red : Colors.blue, ), ], ); } } ``` -------------------------------- ### Customize Dashboard Theme Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Demonstrates how to apply custom colors to the performance dashboard or use built-in light and dark presets. ```dart PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme( backgroundColor: Colors.black87, textColor: Colors.white, warningColor: Colors.amber, errorColor: Colors.redAccent, chartLineColor: Colors.greenAccent, chartFillColor: Colors.greenAccent.withOpacity(0.2), ), ); ``` ```dart PerformanceDashboard(theme: DashboardTheme.light()); PerformanceDashboard(theme: DashboardTheme.dark()); ``` -------------------------------- ### Retrieve Device Information with Device Stream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt This snippet shows how to subscribe to the deviceStream to capture hardware and OS details. The stream emits a DeviceData object once upon initialization, providing model, OS, and manufacturer information. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class DeviceInfoWidget extends StatefulWidget { @override State createState() => _DeviceInfoWidgetState(); } class _DeviceInfoWidgetState extends State { String _model = ''; String _os = ''; String _osVersion = ''; String _manufacturer = ''; @override void initState() { super.initState(); PerformanceMonitor.instance.deviceStream.listen((DeviceData data) { setState(() { _model = data.model; _os = data.os; _osVersion = data.osVersion; _manufacturer = data.manufacturer; }); }); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Model: $_model'), Text('OS: $_os $_osVersion'), Text('Manufacturer: $_manufacturer'), ], ); } } ``` -------------------------------- ### Add Flutter Performance Pulse Dependency Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Instructions for adding the package to your Flutter project via the pubspec.yaml file. ```yaml dependencies: flutter_performance_pulse: ^1.0.6 ``` -------------------------------- ### Monitor Disk Storage and File Operations Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt This snippet shows how to monitor disk storage metrics via diskStream and perform basic file system operations. It provides real-time updates on usage percentages and free space, alongside a utility function for testing file writes and deletions. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; class DiskMonitorWidget extends StatefulWidget { @override State createState() => _DiskMonitorWidgetState(); } class _DiskMonitorWidgetState extends State { double _usagePercent = 0.0; int _freeSpace = 0; int _totalSpace = 0; @override void initState() { super.initState(); PerformanceMonitor.instance.diskStream.listen((DiskData data) { setState(() { _usagePercent = data.usagePercentage; _freeSpace = data.freeSpace; _totalSpace = data.totalSpace; }); }); } String _formatGB(int bytes) { return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB'; } @override Widget build(BuildContext context) { return Column( children: [ Text('Disk Usage: ${_usagePercent.toStringAsFixed(1)}%'), Text('Free: ${_formatGB(_freeSpace)} / ${_formatGB(_totalSpace)}'), LinearProgressIndicator( value: _usagePercent / 100, color: _usagePercent > 90 ? Colors.red : Colors.green, ), ], ); } } Future testDiskOperations() async { final appDir = await getApplicationDocumentsDirectory(); final testFile = File('${appDir.path}/test_file.txt'); await testFile.writeAsString('Test data content'); final fileStats = await testFile.stat(); print('File size: ${fileStats.size} bytes'); await testFile.delete(); } ``` -------------------------------- ### Monitor Frame Rate with FPS Stream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Shows how to subscribe to the fpsStream to receive real-time FpsData updates. This implementation updates the UI based on current FPS values and triggers a warning state when performance drops below the threshold. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class FpsMonitorWidget extends StatefulWidget { @override State createState() => _FpsMonitorWidgetState(); } class _FpsMonitorWidgetState extends State { double _currentFps = 60.0; bool _isWarning = false; @override void initState() { super.initState(); // Subscribe to FPS updates PerformanceMonitor.instance.fpsStream.listen((FpsData data) { setState(() { _currentFps = data.fps; _isWarning = data.isWarning; // true if fps < fpsWarningThreshold }); }); } @override Widget build(BuildContext context) { return Text( 'FPS: ${_currentFps.toStringAsFixed(1)}', style: TextStyle( color: _isWarning ? Colors.red : Colors.green, fontWeight: FontWeight.bold, ), ); } } ``` -------------------------------- ### Logging API with Severity Levels - Dart Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Provides a logging API within PerformanceMonitor supporting multiple severity levels (verbose, debug, info, warning, error). Messages are output via debugPrint with emoji prefixes and respect configured logLevel and showLogs settings. Initialization requires a MonitorConfig object. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; // Initialize with logging configuration await PerformanceMonitor.instance.initialize( config: const MonitorConfig( showLogs: true, logLevel: LogLevel.verbose, // verbose, debug, info, warning, error, none exportLogs: false, ), ); // Log messages at different levels PerformanceMonitor.instance.log('Detailed trace info', level: LogLevel.verbose); // Output: 🔍 VERBOSE: Detailed trace info PerformanceMonitor.instance.log('Debug information', level: LogLevel.debug); // Output: 🐛 DEBUG: Debug information PerformanceMonitor.instance.log('User logged in', level: LogLevel.info); // Output: â„šī¸ INFO: User logged in PerformanceMonitor.instance.log('Memory usage high', level: LogLevel.warning); // Output: âš ī¸ WARNING: Memory usage high PerformanceMonitor.instance.log('Network connection failed', level: LogLevel.error); // Output: ❌ ERROR: Network connection failed // LogLevel hierarchy - each level includes all levels above it // verbose > debug > info > warning > error > none ``` -------------------------------- ### Positioning the Performance Dashboard Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Shows how to position the Performance Dashboard widget within your Flutter application's widget tree using `Positioned`. ```APIDOC ## Positioning the Performance Dashboard ### Description Shows how to position the Performance Dashboard widget within your Flutter application's widget tree using `Positioned`. ### Usage Wrap your `MaterialApp` with a `Stack` and use `Positioned` widgets to place the `PerformanceDashboard`. ### Example ```dart MaterialApp( builder: (context, child) { return Stack( children: [ child!, // Top-right corner const Positioned( right: 16, top: 16, child: PerformanceDashboard(), ), // Or bottom-left corner const Positioned( left: 16, bottom: 16, child: PerformanceDashboard(), ), // Or any other position const Positioned( right: 16, bottom: 16, child: PerformanceDashboard(), ), ], ); }, ) ``` ``` -------------------------------- ### Position Dashboard in UI Source: https://github.com/jamalihassan0307/flutter_performance_pulse/blob/main/README.md Uses a Stack widget within the MaterialApp builder to overlay the performance dashboard at specific screen positions. ```dart MaterialApp( builder: (context, child) { return Stack( children: [ child!, const Positioned( right: 16, top: 16, child: PerformanceDashboard(), ), ], ); }, ); ``` -------------------------------- ### Monitor Battery Status with Battery Stream Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt This snippet demonstrates how to subscribe to the batteryStream to receive real-time updates on battery level and charging state. It uses the BatteryData object to update the UI dynamically based on the device's power status. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; import 'package:battery_plus/battery_plus.dart'; class BatteryMonitorWidget extends StatefulWidget { @override State createState() => _BatteryMonitorWidgetState(); } class _BatteryMonitorWidgetState extends State { int _batteryLevel = 0; bool _isCharging = false; BatteryState _state = BatteryState.unknown; @override void initState() { super.initState(); PerformanceMonitor.instance.batteryStream.listen((BatteryData data) { setState(() { _batteryLevel = data.level; _isCharging = data.isCharging; _state = data.state; }); }); } @override Widget build(BuildContext context) { return Row( children: [ Icon( _isCharging ? Icons.battery_charging_full : Icons.battery_full, color: _batteryLevel < 20 ? Colors.red : Colors.green, ), Text('$_batteryLevel%'), Text(' (${_state.name})'), ], ); } } ``` -------------------------------- ### Monitor Heap Memory Usage in Flutter Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt This snippet demonstrates how to subscribe to the memoryStream to track heap usage in bytes and detect garbage collection events. It updates the UI state whenever new MemoryData is emitted by the performance monitor. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class MemoryMonitorWidget extends StatefulWidget { @override State createState() => _MemoryMonitorWidgetState(); } class _MemoryMonitorWidgetState extends State { int _heapUsage = 0; bool _gcOccurred = false; @override void initState() { super.initState(); PerformanceMonitor.instance.memoryStream.listen((MemoryData data) { setState(() { _heapUsage = data.heapUsage; _gcOccurred = data.hadGC; }); }); } String _formatBytes(int bytes) { if (bytes < 1024) return '$bytes B'; if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB'; return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; } @override Widget build(BuildContext context) { return Row( children: [ Text('Memory: ${_formatBytes(_heapUsage)}'), if (_gcOccurred) const Icon(Icons.recycling, color: Colors.green), ], ); } } ``` -------------------------------- ### Embed Performance Dashboard Widget Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Displays real-time performance metrics using the PerformanceDashboard widget. It is typically wrapped in a Stack to overlay the dashboard on the application UI. ```dart import 'package:flutter/material.dart'; import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( builder: (context, child) { return Stack( children: [ child!, const Positioned( right: 16, bottom: 16, child: Material( elevation: 8, child: PerformanceDashboard( showFPS: true, showCPU: true, showDisk: true, theme: DashboardTheme( backgroundColor: Color(0xFF1E1E1E), textColor: Colors.white, warningColor: Colors.orange, errorColor: Colors.red, chartLineColor: Colors.blue, chartFillColor: Color(0x40808080), ), ), ), ), ], ); }, home: const MyHomePage(), ); } } ``` -------------------------------- ### Dispose PerformanceMonitor Resources Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Shows the proper way to clean up the PerformanceMonitor singleton within a Flutter State object. This ensures that trackers are stopped and resources are released when the widget is disposed or the app is terminated. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; class MyAppState extends State with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { PerformanceMonitor.instance.dispose(); WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.detached) { PerformanceMonitor.instance.dispose(); } } } ``` -------------------------------- ### Monitor API Requests with Network Stream - Dart Source: https://context7.com/jamalihassan0307/flutter_performance_pulse/llms.txt Intercepts HTTP requests made through Dio, logs details like URL, method, status, duration, and response size. It allows subscription to a networkStream to receive NetworkData objects for each request/response cycle. This is useful for debugging and performance analysis of network operations. ```dart import 'package:flutter_performance_pulse/flutter_performance_pulse.dart'; import 'package:dio/dio.dart'; class NetworkMonitorExample extends StatefulWidget { @override State createState() => _NetworkMonitorExampleState(); } class _NetworkMonitorExampleState extends State { final List _requests = []; final Dio _dio = Dio(); // Your Dio instance for making requests @override void initState() { super.initState(); // Subscribe to network request updates PerformanceMonitor.instance.networkStream.listen((NetworkData data) { setState(() { _requests.add(data); }); // Log request details print('${data.method} ${data.url}'); print('Status: ${data.statusCode}'); print('Duration: ${data.duration}ms'); print('Response size: ${data.responseSize} bytes'); if (data.hasError) { print('Error: ${data.errorMessage}'); } }); } Future _makeRequest() async { try { await _dio.get('https://jsonplaceholder.typicode.com/posts'); } catch (e) { print('Request failed: $e'); } } @override Widget build(BuildContext context) { return Column( children: [ ElevatedButton( onPressed: _makeRequest, child: const Text('Make API Request'), ), Expanded( child: ListView.builder( itemCount: _requests.length, itemBuilder: (context, index) { final req = _requests[index]; return ListTile( title: Text('${req.method} ${req.statusCode}'), subtitle: Text('${req.duration}ms - ${req.url}'), trailing: req.hasError ? const Icon(Icons.error, color: Colors.red) : const Icon(Icons.check, color: Colors.green), ); }, ), ), ], ); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.