Search code examples
flutterdartfuturerebuild

Rebuild a FutureBuilder


I am trying to rebuild a FutureBuilder, in my case it is for the purpose of changing the camera that is shown to the user. For that I have to run the Future, the FutureBuilder uses again. The Future currently looks like this:

body: FutureBuilder(
        future: _initializeCameraControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return CameraPreview(_cameraController);
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),

The Future it is running is this one:

Future<void> _initializeCameraControllerFuture;
  @override
  void initState() {
    super.initState();

    if (camerafrontback != true) {
      _cameraController =
          CameraController(widget.camera[0], ResolutionPreset.veryHigh);
    }else{
      _cameraController =
          CameraController(widget.camera[1], ResolutionPreset.veryHigh);
    }
    _initializeCameraControllerFuture = _cameraController.initialize();
  }

I have a button that should trigger this rebuild of the FutureBuilder, it is also changing the 'camerafrontback' Boolean, so that a different camera is used. It is shown below:

IconButton(
            onPressed: () async {
              if (camerafrontback == true){
                setState(() {
                  camerafrontback = false;
                });
              }else{
                setState(() {
                  camerafrontback = true;
                });
              };

            },

At the end, before the last bracket, there must be a statement added that triggers the rebuilds of whole FutureBuilder, but I couldn't find one that suits to my code.

Thanks in advance for your answers!


Solution

  • You need to reinitialize_initializeCameraControllerFuture.

    You can do it something like this

      @override
      void initState() {
        super.initState();
        _init();
      }
    
      ...
    
    
      _init() {
        if (camerafrontback) {
            _cameraController =
              CameraController(widget.camera[1], ResolutionPreset.veryHigh);
    
        } else {
             _cameraController =
              CameraController(widget.camera[0], ResolutionPreset.veryHigh);
        }
        _initializeCameraControllerFuture = _cameraController.initialize();
      }
    
    
      ...
    
    
      IconButton(
      onPressed: () async {
               if (camerafrontback) {
                  camerafrontback = false;
                  setState(_init());
          } else {
                camerafrontback = true;
                 setState(_init);
                 }
               },
             ),