How to add flash toggle button to Flutter camera (flutter_camera_ml_vision)

2,144

I confirm what @tottomotto said in the comments. The feature is currently missing in the camera plugin and the reason torch gives you that error is that controlling the flash can be done only controlling the camera, which is obviously already opened by the plugin.

The only way would be the implementation of the requested feature like the issue said :(

Share:
2,144
Davide Bicego
Author by

Davide Bicego

I'm a web and android software developer! Currently having fun with flutter. I also like guitars but i guess this is not the right place for them ;) I'm software developer at Sintesia S.R.L. always working on KanbanBOX platform, a web service to handle any kanban system.

Updated on December 15, 2022

Comments

  • Davide Bicego
    Davide Bicego over 1 year

    I'm developing an app that has a barcode reader inside it. I'm currently using the package flutter_camera_ml_vision.

    I'm trying to add a flash on/off floating button but i can't activate the flash while the camera is running, only before. error:

    I/System.out(19394): Torch Failed : CAMERA_IN_USE (4): setTorchMode:1732: Torch for camera "0" is not available due to an existing camera user
    

    Also when the camera pops up the flash is disabled.

    How can I achieve this? I'm testing on Android.

    Current code:

    import 'package:firebase_ml_vision/firebase_ml_vision.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:flutter/widgets.dart';
    import 'package:flutter_camera_ml_vision/flutter_camera_ml_vision.dart';
    import 'package:camera/camera.dart';
    import 'package:torch/torch.dart';
    
    class ScanPage extends StatefulWidget {
      @override
      _ScanPageState createState() => _ScanPageState();
    }
    
    class _ScanPageState extends State<ScanPage> {
      bool resultSent = false;
      bool _hasFlash = true;
      bool _isOn = false;
    
      @override
      void initState() {
        super.initState();
        SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
        initPlatformState();
      }
    
      @override
      dispose() {
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeRight,
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
        super.dispose();
      }
    
      initPlatformState() async {
        bool hasFlash = await Torch.hasTorch;
        print("Device has flash ? $hasFlash");
        setState(() { _hasFlash = hasFlash; });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              await _turnFlash();
            },
            child: Icon(_isOn ? Icons.flash_off : Icons.flash_on),
            backgroundColor: Colors.green,
          ),
          body: SafeArea(
            child: SizedBox(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: CameraMlVision<List<Barcode>>(
                resolution: ResolutionPreset.medium,
                detector: FirebaseVision.instance.barcodeDetector().detectInImage,
                onResult: (List<Barcode> barcodes) {
                  if (!mounted || resultSent || barcodes.isEmpty) {
                    return;
                  }
                  resultSent = true;
                  Navigator.of(context).pop<Barcode>(barcodes.first);
                },
              ),
            ),
          ),
        );
      }
    
      Future _turnFlash() async {
        _isOn ? Torch.turnOff() : Torch.turnOn();
        var f = await Torch.hasTorch;
        setState((){
          _hasFlash = f;
          _isOn = !_isOn;
        });
      }
    }