'Making a flash icon work in flutter by turning on the flash when the icon is pressed
I am making a camera app with a button that will be able to turn the flash on and off.
When the flash is not on I would like for the flash_off icon to be displayed.
However, my problem is trying to make the flash turn on and the icon change to flash_auto when the flash icon is pressed. I tried doing something which you can see down below, but I am still new to Flutter and learning the syntax so I do not think it is right.
I also declared the flash variable as a static bool because it would not allow me to declare it as a regular boolean, "static bool flash = false"
const IconButton(
padding: EdgeInsets.only(right: 30), // right 30
onPressed: null,
icon: Icon(
flash ? Icons.flash_on : Icons.flash_off,
color: Colors.white,
),
iconSize: 50,
onPressed: () {
setState(() {
flash = !flash;
flash ? _cameraController.setFlashMode(FlashMode.off);
});
//flash?_cameraController.setFlashMode(FlashMode.torch) :
}),
),
Solution 1:[1]
Because you want three options for icons you can't use a simple true/false check, you'll need an array.
import 'package:flutter/material.dart';
class FlashPage extends StatefulWidget {
const FlashPage({Key? key}) : super(key: key);
@override
State<FlashPage> createState() => _FlashPageState();
}
class _FlashPageState extends State<FlashPage> {
int flashStatus = 0;
List<Icon> flash = [
Icon(Icons.flash_on),
Icon(Icons.flash_off),
Icon(Icons.flash_auto)
];
List<FlashMode> flashMode = [
FlashMode.always,
FlashMode.off,
FlashMode.auto
];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flash demo',
home: Scaffold(
body: Center(
child: IconButton(
icon: flash[flashStatus],
onPressed: () {
setState(() {
flashStatus = (flashStatus + 1) % 3;
_cameraController.setFlashMode(flashMode[flashStatus]);
});
}),
),
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
