如何在Flutter中使用设备闪光灯?求Dart 3兼容方案
Flutter 闪光灯定时开关实现(兼容Dart 3)
兼容Dart 3的第三方包
- camera:官方维护的包,完全适配Dart 3。它不仅支持闪光灯控制,还提供完整的相机功能。可以通过
CameraController的torchMode属性切换闪光灯状态,配合Timer就能实现定时开关。 - torch_light:最新版本已适配Dart 3,API极简,专门用于闪光灯控制,无需处理额外的相机逻辑,只需要申请相机权限即可使用。
无依赖原生实现方式
如果不想用第三方包,可以通过Flutter的MethodChannel直接调用原生系统API,以下是Android和iOS的具体实现:
Android 端步骤
- 在
AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
- 编写Kotlin原生代码处理闪光灯控制:
class MainActivity : FlutterActivity() { private var cameraManager: CameraManager? = null private var cameraId: String? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = cameraManager?.cameraIdList?.firstOrNull() MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "flash_channel").setMethodCallHandler { call, result -> when (call.method) { "turnOnFlash" -> { try { cameraId?.let { cameraManager?.setTorchMode(it, true) } result.success(true) } catch (e: Exception) { result.error("FLASH_ERROR", e.message, null) } } "turnOffFlash" -> { try { cameraId?.let { cameraManager?.setTorchMode(it, false) } result.success(true) } catch (e: Exception) { result.error("FLASH_ERROR", e.message, null) } } else -> result.notImplemented() } } } }
iOS 端步骤
- 在
Info.plist中添加权限描述:
<key>NSCameraUsageDescription</key> <string>需要相机权限来控制闪光灯</string>
- 编写Swift原生代码处理闪光灯控制:
import UIKit import Flutter import AVFoundation class MainFlutterViewController: FlutterViewController { private var captureDevice: AVCaptureDevice? override func viewDidLoad() { super.viewDidLoad() captureDevice = AVCaptureDevice.default(for: .video) let channel = FlutterMethodChannel(name: "flash_channel", binaryMessenger: self.binaryMessenger) channel.setMethodCallHandler { [weak self] call, result in guard let self = self else { return } switch call.method { case "turnOnFlash": do { guard let device = self.captureDevice else { result.error("FLASH_ERROR", "未找到相机设备", nil) return } try device.lockForConfiguration() device.torchMode = .on device.unlockForConfiguration() result.success(true) } catch { result.error("FLASH_ERROR", error.localizedDescription, nil) } case "turnOffFlash": do { guard let device = self.captureDevice else { result.error("FLASH_ERROR", "未找到相机设备", nil) return } try device.lockForConfiguration() device.torchMode = .off device.unlockForConfiguration() result.success(true) } catch { result.error("FLASH_ERROR", error.localizedDescription, nil) } default: result.notImplemented() } } } }
Flutter 端调用与定时逻辑
在Dart代码中,通过MethodChannel调用原生方法,并使用Timer.periodic实现定时开关:
import 'package:flutter/services.dart'; import 'dart:async'; class FlashTimer { static const _channel = MethodChannel('flash_channel'); Timer? _toggleTimer; bool _isFlashActive = false; // 启动定时切换,interval为间隔秒数 void startToggling(double interval) { _toggleTimer?.cancel(); _toggleTimer = Timer.periodic(Duration(seconds: interval.toInt()), (_) async { _isFlashActive = !_isFlashActive; try { if (_isFlashActive) { await _channel.invokeMethod('turnOnFlash'); } else { await _channel.invokeMethod('turnOffFlash'); } } catch (e) { print("闪光灯控制失败: $e"); } }); } // 停止定时并关闭闪光灯 void stopToggling() { _toggleTimer?.cancel(); _channel.invokeMethod('turnOffFlash'); _isFlashActive = false; } }
内容的提问来源于stack exchange,提问作者Anjos
相关产品推荐
相关产品推荐

