Flutter相机插件 [英] 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());
}
是否可以在 initState()
方法中执行此操作?我想这也是关于运行 initState
方法之前所需的异步工作的更一般的问题.(因为 initState
方法不能异步).
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).
我的目标是创建一个 StatefulWidget
,其中包含来自相机的供稿,供其他文件使用.到目前为止,这就是我所拥有的.任何帮助表示赞赏!
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();
}
推荐答案
您无法在 initState
中执行 async
,但是您可以启动已完成的异步工作其他功能,然后在完成 setState
调用后发出信号.使用 await
,您可以确保按照正确的顺序设置摄像机和控制器.最后调用setState将确保在最后重建小部件,您可以在其中将初始化的相机控制器传递到任何地方.
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 ...
}
}
您还希望确保处理任何错误,该程序包包含 CameraException
,当特定于平台的代码失败时会引发该错误.
You also want to make sure you handle any errors, the package includes a CameraException
which is thrown when the platform specific code fails.
这篇关于Flutter相机插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!