Thomas D. Frøysa
Thomas D. Frøysa

Reputation: 698

Flutter Camera Plugin

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

Upvotes: 8

Views: 10747

Answers (1)

Jonah Williams
Jonah Williams

Reputation: 21421

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.

Upvotes: 16

Related Questions