Darshil Shah
Darshil Shah

Reputation: 63

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

I am trying to Use Camera Services using Flutter Camera Package Is there Any Way Available to switch to Front to Back Or Back To Front Camera On Button Click

Upvotes: 6

Views: 17117

Answers (5)

cj0x39e
cj0x39e

Reputation: 171

Now, you can use _controller.setDescription to do this.

I tested on 'camera 0.10.5+5'.

Upvotes: 2

Leandro Ariel
Leandro Ariel

Reputation: 1431

This is my solution:

  List<CameraDescription> cameras = [];
  late CameraController _controller;
  Future<void>? _initializeControllerFuture;

...

  void _toggleCameraLens()
  {
    if (cameras.length <= 2) {
      return;
    }

    final lensDirection = _controller.description.lensDirection;
    if (lensDirection == CameraLensDirection.front)
    {
      setState(() {
        _controller = CameraController(
          cameras.first,
          ResolutionPreset.medium,
        );
      });
    }
    else
    {
      setState(() {
        _controller = CameraController(
          cameras.last,
          ResolutionPreset.medium,
        );
      });
    }

    _initializeControllerFuture = _controller.initialize();
  }

Upvotes: 0

Juan Aguill&#243;n
Juan Aguill&#243;n

Reputation: 369

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();
         
    }

Upvotes: 1

Hitesh Verma
Hitesh Verma

Reputation: 181

Get available cameras and initialise the camera controller with one of them in the 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');
  }

}

Upvotes: 18

chunhunghan
chunhunghan

Reputation: 54427

I have 2 suggestions
1. Please use package 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
enter image description here

  1. In offical example code
    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,
            ),
          ),
        );
      }
    }
    

    enter image description here

Upvotes: 3

Related Questions