torch_flashlight 0.0.3 copy "torch_flashlight: ^0.0.3" to clipboard
torch_flashlight: ^0.0.3 copied to clipboard

A Flutter plugin for controlling torch/flashlight availability, state, blinking, SOS, brightness, and background operation.

torch_flashlight #

A Flutter plugin for controlling torch/flashlight availability, state, blinking, SOS, brightness, and background operation.

pub package

Features #

  • Check torch availability
  • Enable, disable, and query torch state
  • Listen to torch state changes
  • Auto-off timer support
  • Periodic blinking, custom blink patterns, and SOS mode
  • Native blinking for better timing
  • Torch strength control on supported devices
  • Fade in and fade out effects
  • Android foreground service support for background operation
  • Instance-based TorchController API
  • Safe web fallback for unsupported torch operations

Torch State Listener #

Listen to torch state changes in real-time. This feature allows your app to detect when the torch is enabled or disabled, even when the change is triggered by another app.

Check Torch Availability #

Determines if the torch functionality is available on the device. This feature allows your app to check whether the device has a torch (flashlight) and whether it's accessible for use.

Enable Torch #

Enables the torch (flashlight) on the device. This feature turns on the torch, allowing users to utilize their device's flashlight functionality within your app.

Disable Torch #

Disables the torch (flashlight) on the device. This feature turns off the torch, ensuring that the flashlight functionality is no longer active within your app.

Toggle Torch Periodically #

Toggles the torch (flashlight) periodically at specified intervals. This feature allows your app to automatically turn the torch on and off at regular intervals, providing a flashing effect. It can be useful for creating attention-grabbing visual effects or for signaling purposes.

SOS Mode #

Starts SOS mode using the international Morse code distress signal (... --- ...). This feature uses standard Morse code timing for authentic signaling.

  • Dot (short): 200ms on, 200ms off
  • Dash (long): 600ms on, 200ms off
  • Letter space: 600ms off
  • Word space: 1400ms off

Create custom blink patterns for specific signaling needs. Each integer in the pattern represents a duration in milliseconds, alternating between on and off states. Useful for emergency apps and custom signaling.

Torch Strength Control #

Control the brightness/strength of the torch on supported devices. Some Android devices (Android 13+) and iOS devices (iOS 14+) support variable torch strength levels.

Fade In / Fade Out #

Smooth transitions for torch on/off states using torch strength control on supported devices. Falls back to immediate on/off on devices without strength control.

Background Execution #

Enable torch operation while the app is in the background. Useful for emergency apps, cycling lights, and notifications.

Android:

  • Uses foreground service to keep torch running in background
  • Requires additional permissions in AndroidManifest.xml
  • Shows a persistent notification while running

iOS:

  • Requires Background Modes capability in Xcode
  • Configure "Audio, AirPlay, and Picture in Picture" background mode for extended execution

Flash Mode #

Control the flash mode for different use cases. Some OEMs behave differently with torch vs flash modes.

FlashMode.torch - Continuous torch mode (flashlight stays on) FlashMode.flash - Flash mode (brief flash like camera flash)

Native Performance Improvements #

For better performance and more consistent timing, use native blinking instead of Dart timers. Native blinking happens on the platform side, reducing Flutter ↔ platform channel overhead.

Installation #

Add torch_flashlight to your pubspec.yaml file:

dependencies:
  torch_flashlight: ^0.0.3

Install the package by running:

flutter pub get

Import the package in your Dart code:

import 'package:torch_flashlight/torch_flashlight.dart';

Platform Support #

Platform Availability On/off State stream Strength Native blink Background
Android Yes Yes Yes Android 13+ Yes Foreground service
iOS Yes Yes Yes Yes Yes Limited by iOS background modes
Web Returns unsupported fallback No Emits false No No No
macOS/Linux/Windows Registered by plugin template No hardware torch implementation No No No No

Android Setup #

The plugin declares the required camera and foreground service permissions in its Android manifest. If your app uses background torch operation on Android 13+, request notification permission as appropriate for your app before starting the foreground service.

For Android 14+ foreground camera services, make sure your app explains the background flashlight use case clearly to users.

iOS Setup #

Torch control requires a real iOS device with a torch. Simulators do not provide flashlight hardware.

For extended background behavior, configure the required background modes in Xcode based on your app's use case. iOS may still limit background execution.

Usage #

You can use either the static methods from TorchFlashlight class or the instance-based TorchController for a cleaner architecture.

Static Methods (TorchFlashlight) #

The traditional approach using static methods:

await TorchFlashlight.enableTorchFlashlight();
await TorchFlashlight.disableTorchFlashlight();

Instance Methods (TorchController) #

For a cleaner architecture, use the TorchController class:

final controller = TorchController();

// Enable torch
await controller.enable();

// Disable torch
await controller.disable();

// Toggle torch
await controller.toggle();

// Don't forget to dispose when done
controller.dispose();

The TorchController provides all the same functionality as the static methods but with instance-based control, making it easier to manage multiple torch operations and clean up resources.

Platform Capabilities #

Check what features are supported on the current platform:

final capabilities = await TorchFlashlight.getCapabilities();

print('Strength support: ${capabilities.supportsStrength}');
print('Blinking support: ${capabilities.supportsBlinking}');
print('Background support: ${capabilities.supportsBackground}');
print('Fade support: ${capabilities.supportsFade}');
print('SOS support: ${capabilities.supportsSOS}');
print('Custom blink support: ${capabilities.supportsCustomBlink}');

Or using the controller:

final controller = TorchController();
final capabilities = await controller.getCapabilities();

if (capabilities.supportsStrength) {
  await controller.setStrength(5);
}

Torch State Listener #

To listen to torch state changes:

import 'dart:async';

StreamSubscription<bool>? _torchSubscription;

void startListeningToTorchState() {
  _torchSubscription = TorchFlashlight.torchStream.listen((state) {
    print('Torch state: ${state ? "ON" : "OFF"}');
  });
}

void stopListeningToTorchState() {
  _torchSubscription?.cancel();
}

Check Torch Availability #

To check if the torch functionality is available on the device:

  bool isAvailable = await TorchFlashlight.isTorchFlashlightAvailable();

Get Current Torch State #

To get the current torch state (whether it's on or off):

  bool isOn = await TorchFlashlight.isTorchOn();

Get Maximum Torch Strength #

To get the maximum torch strength level supported by the device:

  int maxStrength = await TorchFlashlight.getMaxTorchStrength();

Get Current Torch Strength #

To get the current torch strength level:

  int currentStrength = await TorchFlashlight.getCurrentTorchStrength();

Set Torch Strength #

To set the torch strength level (on supported devices):

  await TorchFlashlight.setTorchStrength(5);

Enable Torch #

To enable the torch (flashlight) on the device:

  await TorchFlashlight.enableTorchFlashlight();

To enable with auto-off timer:

  await TorchFlashlight.enableTorchFlashlight(duration: Duration(minutes: 2));

Disable Torch #

To disable the torch (flashlight) on the device:

  await TorchFlashlight.disableTorchFlashlight();

Toggle Torch Periodically #

To toggle the torch (flashlight) periodically:


  await TorchFlashlight.torchFlashlightEnableDisablePeriodically(
    onOffInterval: Duration(seconds: 1),
    disableTorchRandomlyInSeconds: true,
  );

Stop Torch Toggling #

To stop the torch (flashlight) from toggling periodically:

  await TorchFlashlight.stopTorchFlashlightPeriodically();

Start SOS Mode #

To start SOS mode with Morse code pattern:

  await TorchFlashlight.startSOS();

Stop SOS Mode #

To stop SOS mode:

  await TorchFlashlight.stopSOS();

To start a custom blink pattern:

  await TorchFlashlight.startCustomBlink([100, 100, 300, 100, 100]);

To stop the custom blink pattern:

  await TorchFlashlight.stopCustomBlink();

Fade In #

To fade in the torch smoothly:

  await TorchFlashlight.fadeIn();

With custom duration:

  await TorchFlashlight.fadeIn(duration: Duration(seconds: 1));

Fade Out #

To fade out the torch smoothly:

  await TorchFlashlight.fadeOut();

With custom duration:

  await TorchFlashlight.fadeOut(duration: Duration(seconds: 1));

Start Foreground Service (Android) #

To enable background torch operation on Android:

  await TorchFlashlight.startForegroundService();
  // Now you can start blinking patterns that will continue in background
  await TorchFlashlight.startSOS();

Stop Foreground Service (Android) #

To stop background torch operation:

  await TorchFlashlight.stopForegroundService();

Enable Torch with Flash Mode #

To enable torch with specific flash mode:

  // Continuous torch mode (default)
  await TorchFlashlight.enableTorchFlashlight(mode: FlashMode.torch);

  // Flash mode (brief flash)
  await TorchFlashlight.enableTorchFlashlight(mode: FlashMode.flash);

Start Native Blinking #

For better performance, use native blinking instead of Dart timers:

  // Start native blinking with 500ms interval
  await TorchFlashlight.startNativeBlink(500);

  // Stop native blinking
  await TorchFlashlight.stopNativeBlink();

Using TorchController:

final controller = TorchController();

// Start native blinking
await controller.startNativeBlink(500);

// Stop native blinking
await controller.stopNativeBlink();

API Reference #

Please refer to the API Reference for detailed information on each method.

Support #

For help on usage or to report issues, please open an issue.

License #

The MIT License (MIT) Copyright (c) 2024 Shirsh Shukla

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

6
likes
150
points
91
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for controlling torch/flashlight availability, state, blinking, SOS, brightness, and background operation.

Repository (GitHub)
View/report issues

Topics

#flashlight #torch #camera #blink #sos

License

MIT (license)

Dependencies

flutter, flutter_web_plugins, plugin_platform_interface

More

Packages that depend on torch_flashlight

Packages that implement torch_flashlight