Flutter – How to Turn on Camera Flash
Flutter is a UI toolkit developed and maintained by Google. It was released in May 2017 to the public. It is now one of the most popular cross-platform development frameworks among beginners and experienced application developers. It has a straightforward learning curve and uses the Dart programming language for developing the applications.
Every smartphone generally has a flashlight on the backside of the phone. In this article, we will learn how that flashlight can be controlled in Flutter.
Approach
To control the flashlight in a Flutter app, we will use the camera
package, this package will allow us to access the device’s camera functionalities including the flashlight.
Syntax
await _controller.setFlashMode(FlashMode.torch);
Example Project
The below example project shows how to use the flashlight using the camera package.
Note: Before running this code make sure that you have installed the camera package in your Flutter project. You can do so by running the below command from your project root:
flutter pub add camera
Dart
import 'package:flutter/material.dart' ; import 'package:camera/camera.dart' ; void main() { runApp( const FlashlightApp()); } class FlashlightApp extends StatefulWidget { const FlashlightApp({super.key}); @override _FlashlightAppState createState() => _FlashlightAppState(); } class _FlashlightAppState extends State<FlashlightApp> { late List<CameraDescription> cameras; late CameraController _controller; Color _bgColor = Colors.white; @override void initState() { initializeCamera(); super.initState(); } Future< void > initializeCamera() async { cameras = await availableCameras(); _controller = CameraController(cameras[0], ResolutionPreset.low); await _controller.initialize(); } Future< void > toggleFlashlight() async { if (_controller.value.isInitialized) { if (_controller.value.flashMode == FlashMode.off) { await _controller.setFlashMode(FlashMode.torch); setState(() { _bgColor = Colors.greenAccent; }); } else { await _controller.setFlashMode(FlashMode.off); setState(() { _bgColor = Colors.white; }); } } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( title: "GFG- Flutter Flashlight App" , home: Scaffold( backgroundColor: _bgColor, appBar: AppBar( title: const Text( 'Flutter Flashlight App' ), ), body: Center( child: IconButton( icon: const Icon(Icons.flash_on), onPressed: toggleFlashlight, ), ), ), ); } } |
Output:
Since the back of the phone cannot be recorded on the screen. The background color of the screen is changed to green when the flashlight is on.
Contact Us