Flutter Camera Plugin

你说的曾经没有我的故事 提交于 2021-02-06 11:07:40

问题


I'm new to both Flutter and Dart, and I'm trying to use the Camera Plugin to understand how things work. All examples I find have this part:

List<CameraDescription> cameras;

Future<Null> main() async {
  cameras = await availableCameras();
  runApp(new CameraApp());
}

Is there some way I could do this inside the initState() method? I guess this is also a more general question regarding async work required before the initState-method is run. (As the initState-method cannot be async).

My goal is to create a StatefulWidget containing a feed from the camera, that is used from another file. Here's what I have so far. Any help appreciated!

  List<CameraDescription> cameras;

  @override
  void initState() {
    super.initState();
    getCameras();
    controller = new CameraController(cameras[0], ResolutionPreset.medium);
    controller.initialize().then( (_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

  Future<Null> getCameras() async {
    cameras = await availableCameras();
  }

回答1:


You can't do async work in initState, but you can kick-off async work done in other functions, and then signal when you are done with a setState call. Using await you can make sure the cameras and controller are setup in the correct order. calling setState at the end will make sure the widget gets rebuilt at the end, where you can pass your initialized camera controller wherever you want.

class _CameraState extends State<CameraWidget> {
  List<CameraDescription> cameras;
  CameraController controller;
  bool _isReady = false;

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

  Future<void> _setupCameras() async {
    try {
      // initialize cameras.
      cameras = await availableCameras();
      // initialize camera controllers.
      controller = new CameraController(cameras[0], ResolutionPreset.medium);
      await controller.initialize();
    } on CameraException catch (_) {
      // do something on error.
    }
    if (!mounted) return;
    setState(() {
      _isReady = true;
    });
  }

  Widget build(BuildContext context) {
    if (!_isReady) return new Container();
    return ...
  }
}

You also want to make sure you handle any errors, the package includes a CameraException which is thrown when the platform specific code fails.



来源:https://stackoverflow.com/questions/49640723/flutter-camera-plugin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!