flashlight_control 0.0.2 copy "flashlight_control: ^0.0.2" to clipboard
flashlight_control: ^0.0.2 copied to clipboard

A Flutter plugin for controlling the device flashlight (torch) on iOS and Android.

đŸ”Ļ flashlight_control #

A simple Flutter plugin to control your device's flashlight (torch).

Easily turn the flashlight on or off, check if it's available, and get its current state.


✨ Features #

  • Toggle Flashlight: Quickly switch the flashlight on or off.
  • Check Availability: Determine if the device has a flashlight.
  • Get Current State: Find out whether the flashlight is currently on or off.
  • Android Support: Compatible with Android API level 21 (Lollipop) and above using the Camera2 API.
  • ❌ Not Supported: iOS, Web, and Desktop platforms (due to hardware limitations).

🚀 Installation #

Add the package to your pubspec.yaml:

dependencies:
  flashlight_control: ^1.0.0 # Check for the latest version on pub.dev
copied to clipboard

Then run:

flutter pub get
copied to clipboard

🔐 Android Permissions #

In order to use the flashlight on Android, add the following permissions to your AndroidManifest.xml (inside android/app/src/main/AndroidManifest.xml, before the <application> tag):

<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
copied to clipboard

â„šī¸ Set android:required="true" if your app must have a flashlight or camera to function.


📱 Usage #

Import the package: #

import 'package:flashlight_control/flashlight_control.dart';
copied to clipboard

Example: #

import 'package:flutter/material.dart';
import 'package:flashlight_control/flashlight_control.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(home: FlashlightScreen());
}

class FlashlightScreen extends StatefulWidget {
  @override
  _FlashlightScreenState createState() => _FlashlightScreenState();
}

class _FlashlightScreenState extends State<FlashlightScreen> {
  bool _hasTorch = false;
  bool _isTorchOn = false;
  String _statusMessage = 'Checking flashlight availability...';

  @override
  void initState() {
    super.initState();
    _initFlashlight();
  }

  Future<void> _initFlashlight() async {
    try {
      final hasTorch = await FlashlightControl.hasTorch();
      setState(() {
        _hasTorch = hasTorch;
        _statusMessage = hasTorch
            ? 'Flashlight available!'
            : 'No flashlight found on this device.';
      });

      if (hasTorch) {
        final isOn = await FlashlightControl.isOn();
        setState(() => _isTorchOn = isOn);
      }
    } on PlatformException catch (e) {
      setState(() => _statusMessage = 'Error: ${e.message}');
    } catch (e) {
      setState(() => _statusMessage = 'Unexpected error: $e');
    }
  }

  Future<void> _toggleFlashlight() async {
    if (!_hasTorch) {
      setState(() => _statusMessage = 'No flashlight available to toggle.');
      return;
    }

    try {
      if (_isTorchOn) {
        await FlashlightControl.turnOff();
        setState(() {
          _isTorchOn = false;
          _statusMessage = 'Flashlight turned OFF.';
        });
      } else {
        await FlashlightControl.turnOn();
        setState(() {
          _isTorchOn = true;
          _statusMessage = 'Flashlight turned ON.';
        });
      }
    } on PlatformException catch (e) {
      setState(() => _statusMessage = 'Error: ${e.message}');
    } catch (e) {
      setState(() => _statusMessage = 'Unexpected error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flashlight Control')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_statusMessage, textAlign: TextAlign.center),
            const SizedBox(height: 20),
            if (_hasTorch)
              Icon(
                _isTorchOn ? Icons.lightbulb : Icons.lightbulb_outline,
                size: 80,
                color: _isTorchOn ? Colors.yellow[700] : Colors.grey,
              ),
            const SizedBox(height: 20),
            if (_hasTorch)
              ElevatedButton(
                onPressed: _toggleFlashlight,
                child: Text(_isTorchOn ? 'Turn Off' : 'Turn On'),
              ),
            if (!_hasTorch)
              const Text(
                'Cannot control flashlight.',
                style: TextStyle(color: Colors.red),
              ),
          ],
        ),
      ),
    );
  }
}
copied to clipboard

📘 API Reference #

FlashlightControl.hasTorch() → Future<bool> #

Checks if the device has a flashlight.

FlashlightControl.turnOn() → Future<bool> #

Turns the flashlight on. May throw PlatformException.

FlashlightControl.turnOff() → Future<bool> #

Turns the flashlight off. May throw PlatformException.

FlashlightControl.isOn() → Future<bool> #

Returns true if the flashlight is currently on, otherwise false.


🧩 Troubleshooting #

  • PlatformException(UNAVAILABLE, No flashlight found...)
    → Your device may not have a flashlight or the plugin couldn't access it.

  • PlatformException(ERROR, Failed to turn on flashlight...)
    → Check for camera hardware issues or permission problems.

  • MissingPluginException
    → Run flutter pub get, then try flutter clean and flutter run. Restart your IDE if needed.

  • Build Error (minSdkVersion)
    → Ensure minSdkVersion in android/app/build.gradle is 21 or higher:

    defaultConfig {
        minSdkVersion 21
    }
    
    copied to clipboard

🤝 Contributing #

We welcome contributions! If you spot a bug, want to suggest a feature, or submit a pull request, please head over to the GitHub repository.


📝 License #

This project is licensed under the MIT License. See the LICENSE file for more details.

1
likes
140
points
134
downloads

Publisher

unverified uploader

Weekly Downloads

2024.08.26 - 2025.07.21

A Flutter plugin for controlling the device flashlight (torch) on iOS and Android.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on flashlight_control