flutter LateInitializationError无法理解原因

4si2a6ki  于 2023-06-30  发布在  Flutter
关注(0)|答案(4)|浏览(278)

我正在Flutter中构建一个应用程序,我正在尝试打开相机进行预览。我一直得到错误LateInitializationError: Field _cameraController我不明白为什么会发生。我的代码是相当小的,我不明白为什么它的抱怨。

late List<CameraDescription> cameras;

class AddPostPage extends StatefulWidget {
  const AddPostPage({super.key});

  @override
  _AddPostPageState createState() => _AddPostPageState();
}

class _AddPostPageState extends State<AddPostPage> {
  late CameraController _cameraController;

  @override
  void initState() {
    availableCameras().then((value) {
      cameras = value;
      if (cameras.isEmpty) {}
      _initCameraController(cameras[0]).then((void v) {});
    });
    super.initState();
  }

  Future _initCameraController(CameraDescription cameraDescription) async {
    await _cameraController.dispose();
    _cameraController =
        CameraController(cameraDescription, ResolutionPreset.high);

    _cameraController.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
    try {
      await _cameraController.initialize();
    } on Exception catch (exception) {
      print(exception);
    }

    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (BuildContext context, SizingInformation sizingInformation) {
        return Scaffold(
            body: Stack(
          children: [
            Container(
              height: double.infinity,
              child: CameraPreview(_cameraController),
            )
          ],
        ));
      },
    );
  }

  @override
  void dispose() {
    _cameraController.dispose();
    super.dispose();
  }
}

它发生在运行时,当按下按钮,以访问相机在我的应用程序。我用的是iOS模拟器
知道为什么吗

egmofgnx

egmofgnx1#

不允许在late变量尚未初始化时使用它们。在你的代码中有三个地方可能是这样的:

await _cameraController.dispose();

...

child: CameraPreview(_cameraController),

...

_cameraController.dispose();

这将是更好地使它空,而不是晚,所以改变

late CameraController _cameraController;

CameraController? _cameraController;

然后您可以将用法更改为

await _cameraController?.dispose();

...

child: _cameraController == null ? CircularProgressIndicator() : CameraPreview(_cameraController!),

...

_cameraController?.dispose();

例如。

wvmv3b1j

wvmv3b1j2#

可能是你尝试检查如果_cameraController.value.isInitialized加载camerapreview之前

@override   Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (BuildContext context, SizingInformation sizingInformation) {
        return Scaffold(
            body: Stack(
          children: [
            Container(
              height: double.infinity,
              child:  (_cameraController!=null&&_cameraController.value.isInitialized)? 
                     CameraPreview(_cameraController):
                     Center(
                      child: CircularProgressIndicator()
                      ),),
          ],
        ));
      },
    );
}
aydmsdu9

aydmsdu93#

加载时_cameraController未初始化,CameraPreview可能是罪魁祸首。我会将_cameraController改为nullable。
build中,如果_cameraController == null返回一个指示符或其他小部件,例如Text('Loading ...)`
然后,一旦在SetState中设置了_cameraController,它将重新构建,而不是空值,并且应该加载。

i86rm4rw

i86rm4rw4#

late List<CameraDescription> cameras;

class AddPostPage extends StatefulWidget {
  const AddPostPage({super.key});

  @override
  _AddPostPageState createState() => _AddPostPageState();
}

class _AddPostPageState extends State<AddPostPage> {
  final  CameraController? _cameraController; //Make change on this line//

  @override
  void initState() {
    availableCameras().then((value) {
      cameras = value;
      if (cameras.isEmpty) {}
      _initCameraController(cameras[0]).then((void v) {});
    });
    super.initState();
  }

  Future _initCameraController(CameraDescription cameraDescription) async {
    await _cameraController.dispose();
    _cameraController =
        CameraController(cameraDescription, ResolutionPreset.high);

    _cameraController.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
    try {
      await _cameraController.initialize();
    } on Exception catch (exception) {
      print(exception);
    }

    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (BuildContext context, SizingInformation sizingInformation) {
        return Scaffold(
            body: Stack(
          children: [
            Container(
              height: double.infinity,
              child: CameraPreview(_cameraController),
            )
          ],
        ));
      },
    );
  }

  @override
  void dispose() {
    _cameraController.dispose();
    super.dispose();
  }
}

相关问题