重建一个 FutureBuilder

Rebuild a FutureBuilder

我正在尝试重建 FutureBuilder,在我的例子中,它是为了更改显示给用户的相机。为此,我必须 运行 Future,再次使用 FutureBuilder。 未来目前看起来像这样:

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

未来是运行宁是这个:

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

我有一个应该触发 FutureBuilder 重建的按钮,它也在更改 'camerafrontback' 布尔值,以便使用不同的相机。如下图:

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

            },

最后,在最后一个括号之前,必须添加一条语句来触发整个 FutureBuilder 的重建,但我找不到适合我代码的语句。

提前感谢您的回答!

您需要重新初始化_initializeCameraControllerFuture

你可以这样做

  @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);
             }
           },
         ),

要完全重建您的屏幕,您只需将屏幕替换为相同的屏幕即可

Navigator.pushReplacement(context,
  MaterialPageRoute(
    builder: (BuildContext context) =>
       *SamePage*()
  )
);