How to use device's flashlight in flutter?

1k Views Asked by At

I want to use device's flashlight in my flutter applications, to turn it on and off in certain intervals, and I am looking for a way to use it.

All packages I found on pub.dev are not dart 3 compatible as for now, so I was wondering is there some other package that you know of that can help me with this or if I can do it somehow without package?

Thanks

2

There are 2 best solutions below

0
Harsh Panchal On

There are several packages(compatible with Dart 3) for using device's flashlight as below:

  • torch_controller for toggling the flashlight, checking the status of flashlight, etc.

  • torch_light for managing the device torch

  • Also you can use the class android.hardware.camera2.CameraManager to access the torch for Android.

0
Darshan Kachhadiya On

use camera Dependency and try this demo:

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

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

  @override
  State<CameraFlashLightScreen> createState() => _CameraFlashLightScreenState();
}

class _CameraFlashLightScreenState extends State<CameraFlashLightScreen> {
  late CameraController cameraController;
  late Future<void> cameraInitializeFuture;
  late bool _isFlashOn = false;

  @override
  void initState() {
    super.initState();
    cameraInitializeFuture = initializeCamera();
  }

  Future<void> initializeCamera() async {
    final cameras = await availableCameras();
    final backCamera = cameras.firstWhere(
      (camera) => camera.lensDirection == CameraLensDirection.back,
      orElse: () => cameras.first,
    );

    cameraController = CameraController(
      backCamera,
      ResolutionPreset.low,
    );

    await cameraController.initialize();
  }

  Future<void> toggleFlashLight() async {
    try {
      if (_isFlashOn) {
        await cameraController.setFlashMode(FlashMode.off);
      } else {
        await cameraController.setFlashMode(FlashMode.torch);
      }
      setState(() {
        _isFlashOn = !_isFlashOn;
      });
    } catch (e) {}
  }

  @override
  void dispose() {
    cameraController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flashlight App'),
      ),
      body: FutureBuilder<void>(
        future: cameraInitializeFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Center(
              child: ElevatedButton(
                onPressed: toggleFlashLight,
                child: Text(
                    _isFlashOn ? 'Turn Off Flashlight' : 'Turn On Flashlight'),
              ),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}