Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Camera Plugin

Tags:

flutter

dart

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();
  }
like image 988
Thomas D. Frøysa Avatar asked Apr 03 '18 23:04

Thomas D. Frøysa


1 Answers

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.

like image 127
Jonah Williams Avatar answered Oct 05 '22 14:10

Jonah Williams