Navin Kumar
Navin Kumar

Reputation: 4027

Flutter CamerPlugin "camera preview" freezed when app goes to background

Hi iam using flutter cameraPreview to capture photo, the camera preview works fine but when the camera screen goes to background, while on resumed on that screen the camera screen is frezzed, cant able to view cameraPrview onResume.

mycode:

Future<void> _initializeCamera() async {
final cameras = await availableCameras();
final firstCamera = cameras.first;
_controller = CameraController(firstCamera, ResolutionPreset.high);
_initializeControllerFuture = _controller.initialize();
if (!mounted) {
  return;
}
setState(() {
  isCameraReady = true;
});
}


@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: Stack(children: <Widget>[
        FutureBuilder<void>(
          future: _initializeControllerFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              // If the Future is complete, display the preview.
              return CameraPreview(_controller);
            } else {
              return Center(
                  child:
                      CircularProgressIndicator()); // Otherwise, display a loading indicator.
            }
          },
        ),],),);

controller is disposed prpoperly.

I want to know why camera preview is disposed while pause.

Upvotes: 1

Views: 4993

Answers (2)

SimpleXination
SimpleXination

Reputation: 11

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';

late List<CameraDescription> _cameras;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  _cameras = await availableCameras();
  runApp(const CameraApp());
}

/// CameraApp is the Main Application.
class CameraApp extends StatefulWidget {
  /// Default Constructor
  const CameraApp({Key? key}) : super(key: key);

  @override
  State<CameraApp> createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> with WidgetsBindingObserver {
  late CameraController controller;
  // late AppLifecycleState _appLifecycleState;

  @override
  void initState() {
    super.initState();
    // _appLifecycleState = AppLifecycleState.resumed;
    WidgetsBinding.instance.addObserver(this);
    controller = CameraController(_cameras[0], ResolutionPreset.max);
    cameraInit();
  }

  void cameraInit() {
    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // Handle access errors here.
            break;
          default:
            // Handle other errors here.
            break;
        }
      }
    });
  }

  @override
  void dispose() {
    controller.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      // _appLifecycleState = state;
    });
    if (state == AppLifecycleState.resumed) {
      // App is in the foreground
      print('App is in the foreground');

      cameraInit();
    } else if (state == AppLifecycleState.paused) {
      // App is in the background
      print('App is in the background');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!controller.value.isInitialized) {
      return Container();
    }
    return MaterialApp(
      home: CameraPreview(controller),
    );
  }
}

Upvotes: 1

Navin Kumar
Navin Kumar

Reputation: 4027

Issue is solved by initialised cameraPreview onResume

 @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _controller != null
          ? _initializeControllerFuture = _controller.initialize()
          : null; //on pause camera disposed so we need call again "issue is only for android"
    }
  }

On resuming to the page, _controller.initialize will call, so that cameraPreview will works fine.

This is due to cameraPreview runs for long on onPause, it will be disposed..onAndroid i think so..

Upvotes: 9

Related Questions