Posted in

Switch ON or OFF Flashlight With Flutter

Switch ON or OFF Flashlight With Flutter
Switch ON or OFF Flashlight With Flutter

Looking to add a flashlight or torch feature to your Flutter app? You’re in the right place. Whether you’re building a utility app, adding a handy feature for users in low-light conditions, or just want to control the device’s camera flash, Flutter makes it surprisingly simple.

In this guide, we’ll walk you through everything you need to switch the device flashlight ON or OFF. We’ll use a popular and reliable package, cover the necessary setup for both Android and iOS, and provide a complete, practical code example.

Finding the Right Tool: The torch_light Package

While you could write native platform-specific code to control the flashlight, a pre-built package saves a ton of time and handles the complexities for you. For this task, we recommend the torch_light package. It’s lightweight, easy to use, and provides the core functionality we need.

To get started, add it to your pubspec.yaml file:

YAML

dependencies:
  flutter:
    sdk: flutter
  torch_light: ^1.0.0 # Check for the latest version on pub.dev
Dart

After adding the dependency, run flutter pub get in your terminal to install the package.

Platform-Specific Setup: Permissions are Key 🔑

To control the flashlight, your app needs permission from the operating system. The setup is slightly different for Android and iOS.

Android Setup

For Android, you need to declare the FLASHLIGHT and CAMERA permissions in your AndroidManifest.xml file. The flashlight is considered a part of the camera hardware, which is why both are often required.

Navigate to android/app/src/main/AndroidManifest.xml and add the following lines inside the <manifest> tag:

XML

<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
Dart

This tells Android that your app intends to use the camera and its flash unit.

iOS Setup

For iOS, you need to provide a description for why your app needs to access the camera. This description is shown to the user when the app first requests permission.

Navigate to ios/Runner/Info.plist and add the following key-value pair:

XML

<key>NSCameraUsageDescription</key>
<string>This app needs camera access to control the flashlight.</string>
Dart

You can customize the string value to better match your app’s functionality.

Implementing the Flashlight Toggle in Your App

Now for the fun part: writing the Dart code! We’ll create a simple UI with a single button to toggle the flashlight on and off.

First, import the necessary package in your Dart file:

Dart

import 'package:torch_light/torch_light.dart';
Dart

Next, let’s build the UI and logic. The core of the functionality lies in checking if the device has a flash and then enabling or disabling it.

Here’s a complete example of a stateful widget that handles this:

Dart

import 'package:flutter/material.dart';
import 'package:torch_light/torch_light.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flashlight Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const FlashlightScreen(),
    );
  }
}

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

  @override
  _FlashlightScreenState createState() => _FlashlightScreenState();
}

class _FlashlightScreenState extends State<FlashlightScreen> {
  bool _isFlashlightOn = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('FlutterStuff Flashlight Control'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              _isFlashlightOn ? Icons.flash_on : Icons.flash_off,
              size: 100,
              color: _isFlashlightOn ? Colors.yellow : Colors.grey,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleFlashlight,
              child: Text(_isFlashlightOn ? 'Turn OFF' : 'Turn ON'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _toggleFlashlight() async {
    try {
      if (_isFlashlightOn) {
        await TorchLight.disableTorch();
      } else {
        await TorchLight.enableTorch();
      }
      setState(() {
        _isFlashlightOn = !_isFlashlightOn;
      });
    } on Exception catch (_) {
      // Handle error, e.g., show a snackbar
      _showErrorSnackbar('Could not control the flashlight.');
    }
  }

  void _showErrorSnackbar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
      ),
    );
  }
}
Dart

Code Breakdown:

  1. State Management: We use a boolean _isFlashlightOn to keep track of the flashlight’s current state.
  2. UI: An Icon visually represents the state (on or off), and an ElevatedButton triggers the action.
  3. _toggleFlashlight Method: This async function is where the magic happens.
    • It checks the _isFlashlightOn flag.
    • If the light is on, it calls TorchLight.disableTorch().
    • If the light is off, it calls TorchLight.enableTorch().
    • setState is called to rebuild the UI with the new state.
  4. Error Handling: It’s crucial to wrap the torch_light calls in a try...catch block. An exception can occur if the device doesn’t have a flashlight or if there’s a permission issue. We show a SnackBar to inform the user of any errors.

Best Practices and Final Thoughts

  • Check for Availability: Before attempting to turn on the torch, you can check if the device even has one using TorchLight.isTorchAvailable(). This can help prevent errors and create a better user experience on devices without a flash.
  • Handle App Lifecycle: Consider the app’s lifecycle. You might want to automatically turn the flashlight off when the app goes into the background to save battery. You can use a WidgetsBindingObserver for this.
  • Inform the User: Always let the user know why you need camera permission. A clear explanation in your Info.plist (for iOS) builds trust.

And that’s it! You now have a fully functional flashlight toggle in your Flutter application. This simple yet powerful feature can add significant value for your users.

Anynew24.com Is A Team Of Passionate Flutter Developers On A Mission To Empower The Community. We Share Our Expertise And Insights Through Comprehensive Guides, Tutorials, And Resources, Making Flutter Mobile App Development Accessible And Enjoyable For Everyone.

Leave a Reply