Search code examples
fluttericonstoggletorch

create on off toggle Icon for flutter torch


I tried to implement the possibility to use the flash of the phone as a torch in my flutter app. The on/ off button is located in the appbar. This runs fine except the light on and light off Button appear both at the same time. How can I make it, that either one or the other is shown. depending on whether the lamp is on or off? Thank you very much for your help I used the flutter torch_light: ^0.4.0


Class TorchController extends StatelessWidget {
  const TorchController({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: FutureBuilder<bool>(
        future: _isTorchAvailable(context),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData && snapshot.data!) {
            return Column(
              children: [
                Expanded(
                  child: Center(
                    child: IconButton ( icon: const Icon(Icons.flashlight_on_outlined,size: 35,),


                      onPressed: () async {
                        _enableTorch(context);
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Center(
                    child: IconButton (icon: const Icon(Icons.flashlight_off_outlined,size: 35,),


                      onPressed: () async {
                        _disableTorch(context);
                      },
                    ),
                  ),
                ),
              ],
            );
          } else if (snapshot.hasData) {
            return const Center(
              child: Text('No torch available.'),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

 Future<bool> _isTorchAvailable(BuildContext context) async {
   try {
    return await TorchLight.isTorchAvailable();
    } on Exception catch (_) {
      _showMessage(
        'Could not check if the device has an available torch',
       context,
      );
      rethrow;
    }
  }

  Future<void> _enableTorch(BuildContext context) async {
    try {
      await TorchLight.enableTorch();
    } on Exception catch (_) {
      _showMessage('Could not enable torch', context);
    }
  }

  Future<void> _disableTorch(BuildContext context) async {
    try {
      await TorchLight.disableTorch();
    } on Exception catch (_) {
      _showMessage('Could not disable torch', context);
    }
  }

  void _showMessage(String message, BuildContext context) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }
}
//Ende```

Solution

  • First of all, change the widget from stateless to stateful widget. Then

    1. define a variable to show the status of the torch
      • isTorchOn = false;
    2. on _enableTorch() update the value to true

    (no need to pass context as it is now a stateful widget)

    Future<void> _enableTorch(BuildContext context) async {
            try {
              await TorchLight.enableTorch();
              setState(()=> isTorchOn = true);
            } on Exception catch (_) {
              _showMessage('Could not enable torch', context);
            }
          }

    1. do the same for _disableTorch() as set isTorchOn to false

    Future<void> _disableTorch(BuildContext context) async {
        try {
          await TorchLight.disableTorch();
          setState(()=> isTorchOn = false);
        } on Exception catch (_) {
          _showMessage('Could not disable torch', context);
        }
      }