How correctly pause camera when user moved to other (preview) screen?
Have a variable like _cameraOn = true. Show CameraPreview when it is true and not when it is false. While navigating to another screen set it to false
You could have the camera related functionality in a separate widget. So every time it is displayed it is initialized, and when it is not it’s disposed.
A simple working example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import 'dart:async'; import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; List<CameraDescription> cameras; Future<void> main() async { cameras = await availableCameras(); runApp(MaterialApp( home: CameraApp(), )); } class CameraApp extends StatefulWidget { @override _CameraAppState createState() => _CameraAppState(); } class _CameraAppState extends State<CameraApp> { bool _cameraOn = true; @override Widget build(BuildContext context) { return Scaffold( body: Column( children: <Widget>[ Expanded( child: _cameraOn ? Camera() : Container(), ), FlatButton( onPressed: () { setState(() { _cameraOn = false; }); Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => Post())).then((res) { setState(() { _cameraOn = true; }); }).catchError((err) { print(err); }); }, child: Text("NEXT PAGE"), ), ], ), ); } } class Camera extends StatefulWidget { @override _CameraState createState() => _CameraState(); } class _CameraState extends State<Camera> { CameraController controller; @override void initState() { super.initState(); controller = CameraController(cameras[0], ResolutionPreset.medium); controller.initialize().then((_) { if (!mounted) { return; } setState(() {}); }); } @override Widget build(BuildContext context) { if (!controller.value.isInitialized) { return Container(); } return AspectRatio( aspectRatio: controller.value.aspectRatio, child: CameraPreview(controller), ); } @override void dispose() { controller?.dispose(); super.dispose(); } } class Post extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Text("Post"), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.