import 'package:camera/camera.dart';
import 'dart:async';
import 'package:flutter/material.dart';
class CameraMgr{
CameraMgr._();
CameraController _cameraCtrl;
Future<CameraController> openCamera() async {
CameraDescription cameraDescription;
List<CameraDescription> cameras = await availableCameras();
for (CameraDescription xx in cameras){
if(xx.lensDirection==CameraLensDirection.front){
cameraDescription = xx;
break;
}
}
if(cameraDescription==null){
return null;
}
if (_cameraCtrl != null) {
await _cameraCtrl.dispose();
}
_cameraCtrl = new CameraController(cameraDescription, ResolutionPreset.low)..addListener(() {
if (_cameraCtrl.value.hasError) {
print("");
}
});
try {
await _cameraCtrl.initialize();
} on CameraException catch (e) {
print(e);
}
return _cameraCtrl;
}
close()async {
if (_cameraCtrl != null) {
await _cameraCtrl.dispose();
}
_cameraCtrl = null;
}
}
CameraMgr myCameraMgr = new CameraMgr._();
class TestCamera extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return new _TestCameraState();
}
}
class _TestCameraState extends State<TestCamera>{
@override
void initState() {
super.initState();
myCameraMgr.openCamera();
}
@override
void dispose(){
super.dispose();
myCameraMgr.close();
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
backgroundColor: Colors.blueAccent,
body: new Center(
child: new LayoutBuilder(
builder: (BuildContext ctx,BoxConstraints bcts){
return new GestureDetector(
child: new Container(
height: 80.0,
color: Colors.red[100],
child: new Text("touch to show dialog"),
),
onTap: ()async{
CameraController ctrl = await myCameraMgr.openCamera();
showDialog(
context: ctx,
builder: (BuildContext _){
return new Container(
height: bcts.maxHeight,
width: bcts.maxWidth,
child: new DialogCamera(ctrl),
);
}
);
},
);
},
)
),
),
);
}
}
class DialogCamera extends StatelessWidget{
DialogCamera(this.ctrl);
final CameraController ctrl;
@override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.all(150.0),
child: new Center(
child: new CameraPreview(this.ctrl),
),
);
}
}
void main() {
runApp(new TestCamera());
}
There is my test case above. In my app,I need show and take photo by CameraPreview frequently,but the Initialization of the widget is too slow.