简体   繁体   English

有没有办法在 Flutter 中的 onPressed() 事件上切换相机?

[英]Is there Any Way to Switch Camera on onPressed() Event In Flutter?

我正在尝试使用 Flutter 相机包使用相机服务是否有任何方法可以在按钮单击时切换到前后或后到前摄像头

Get available cameras and initialise the camera controller with one of them in the initState().获取可用的相机并在 initState() 中使用其中一个来初始化相机控制器。 Also, store the available cameras to a class variable.此外,将可用的相机存储到类变量中。

 CameraController _controller;
 List<CameraDescription> _availableCameras;

 @override
 void initState() {
   super.initState();
   _getAvailableCameras();
 }

 // get available cameras
 Future<void> _getAvailableCameras() async{
   WidgetsFlutterBinding.ensureInitialized();
   _availableCameras = await availableCameras();
   _initCamera(_availableCameras.first);
 }

 // init camera
 Future<void> _initCamera(CameraDescription description) async{
  _controller = CameraController(description, ResolutionPreset.max, enableAudio: true);

  try{
    await _controller.initialize();
    // to notify the widgets that camera has been initialized and now camera preview can be done
    setState((){}); 
  }
  catch(e){
    print(e);
  }  
}

Just re-initialize the camera controller with a new camera description on button click.只需在单击按钮时使用新的相机描述重新初始化相机控制器。

void _toggleCameraLens() {
 // get current lens direction (front / rear)
 final lensDirection =  _controller.description.lensDirection;
 CameraDescription newDescription;
 if(lensDirection == CameraLensDirection.front){
    newDescription = _availableCameras.firstWhere((description) => description.lensDirection == CameraLensDirection.back);
 }
 else{
    newDescription = _availableCameras.firstWhere((description) => description.lensDirection == CameraLensDirection.front);
 }

  if(newDescription != null){
    _initCamera(newDescription);
  }
  else{
    print('Asked camera not available');
  }

} }

I have 2 suggestions我有2个建议
1. Please use package camera_camera https://github.com/gabulsavul/camera_camera 1. 请使用包camera_camera https://github.com/gabulsavul/camera_camera
It provide a good example and a lot functions already.它已经提供了一个很好的例子和很多功能。
You can use this package directly or modify it.你可以直接使用这个包,也可以修改它。
screen of this package这个包的屏幕
在此处输入图片说明

  1. In offical example code在官方示例代码中
    https://github.com/flutter/plugins/blob/master/packages/camera/example/lib/main.dart https://github.com/flutter/plugins/blob/master/packages/camera/example/lib/main.dart
    switch camera via this function通过此功能切换相机
    You can use this example directly你可以直接使用这个例子

    void onNewCameraSelected(CameraDescription cameraDescription) async { if (controller != null) { await controller.dispose(); } controller = CameraController( cameraDescription, ResolutionPreset.high, enableAudio: enableAudio, ); // If the controller is updated then update the UI. controller.addListener(() { if (mounted) setState(() {}); if (controller.value.hasError) { showInSnackBar('Camera error ${controller.value.errorDescription}'); } }); try { await controller.initialize(); } on CameraException catch (e) { _showCameraException(e); } if (mounted) { setState(() {}); } }

    Display a row of toggle to select the camera显示一行切换选择相机

     Widget _cameraTogglesRowWidget() { final List<Widget> toggles = <Widget>[]; if (cameras.isEmpty) { return const Text('No camera found'); } else { for (CameraDescription cameraDescription in cameras) { toggles.add( SizedBox( width: 90.0, child: RadioListTile<CameraDescription>( title: Icon(getCameraLensIcon(cameraDescription.lensDirection)), groupValue: controller?.description, value: cameraDescription, onChanged: controller != null && controller.value.isRecordingVideo ? null : onNewCameraSelected, ), ), ); } }

    在此处输入图片说明

You can do something like this:你可以这样做:

onTap: () {
      this.setState(() {
        /// Change the current selected camera State.
        this.selectedCamera =this.selectedCamera == 0 ? 1 : 0;
      });

      this._cameraController = CameraController(
          this._camerasAvailable[this.selectedCamera],
          ResolutionPreset.max,
      );
      /// Reinit camera.
      this.cameraInitialize = this._cameraController.initialize();
         
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM