flashlight_control 0.0.2
flashlight_control: ^0.0.2 copied to clipboard
A Flutter plugin for controlling the device flashlight (torch) on iOS and Android.
example/lib/flashlight_control_example.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flashlight_control/flashlight_control.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isTorchAvailable = false;
bool _isTorchOn = false;
@override
void initState() {
super.initState();
_checkTorchAvailability();
_checkTorchState(); // Initial check for torch state
}
Future<void> _checkTorchAvailability() async {
bool available;
try {
available = await FlashlightControl.hasTorch();
} on Exception {
available = false;
}
setState(() {
_isTorchAvailable = available;
});
}
Future<void> _checkTorchState() async {
bool on;
try {
on = await FlashlightControl.isOn();
} on Exception {
on = false;
}
setState(() {
_isTorchOn = on;
});
}
Future<void> _toggleTorch() async {
if (!_isTorchAvailable) return;
bool success;
if (_isTorchOn) {
success = await FlashlightControl.turnOff();
} else {
success = await FlashlightControl.turnOn();
}
if (success) {
setState(() {
_isTorchOn = !_isTorchOn;
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flashlight Plugin Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Torch Available: ${_isTorchAvailable ? "Yes" : "No"}'),
const SizedBox(height: 20),
if (_isTorchAvailable)
ElevatedButton(
onPressed: _toggleTorch,
child: Text(_isTorchOn ? 'Turn Off Flashlight' : 'Turn On Flashlight'),
),
],
),
),
),
);
}
}