initShakeListener static method

void initShakeListener({
  1. required dynamic onSubmit(
    1. ReportFormData formData
    ),
  2. double shakeThreshold = 40.0,
  3. Widget? customScreen,
  4. bool takeScreenshot = true,
})

Initializes the shake listener and navigates to the report screen when a shake is detected.

Implementation

static void initShakeListener(
    {required Function(ReportFormData formData) onSubmit,
    double shakeThreshold = 40.0,
    Widget? customScreen,
    bool takeScreenshot = true}) async {
  // Send the shakeThreshold value to the native platform
  await _methodChannel
      .invokeMethod('setShakeThreshold', {'threshold': shakeThreshold});

  /// Set up the stream for shake detection
  _shakeStream ??= _eventChannel.receiveBroadcastStream().map((_) {});

  /// Listen for shake events
  _shakeStream!.listen((_) async {
    if (!_isReporting) {
      _isReporting = true;

      File? screenshotFile;

      if (takeScreenshot) {
        // Capture the screenshot of the entire current screen
        final image = await _screenshotController.capture(
            delay: const Duration(milliseconds: 500));
        if (image != null) {
          final directory = await getTemporaryDirectory();
          final String filePath =
              '${directory.path}/screenshot_${DateTime.now().millisecondsSinceEpoch}.png';
          screenshotFile = File(filePath);
          await screenshotFile.writeAsBytes(image);
        }
      }

      /// Navigates to the report screen.
      ///
      /// report screen will allow users to submit feedback or reports.
      navigatorKey.currentState
          ?.push(
        MaterialPageRoute(
          builder: (context) => ReportScreen(
            screenshotFile: screenshotFile,
            onSubmit: (formData) {
              onSubmit(formData);
            },
          ),
        ),
      )
          .then((_) {
        _isReporting = false;
        screenshotFile?.delete();
      });
    }
  });
}