简体   繁体   中英

Flutter the application crashed when I change the Camera

I'm trying to write a flutter application to test the front and the back camera.

First the user opens the back camera and a question will be displayed if the image is clear.
Then they will take a photo after they will be asked if if the photo is clear. Then I change camera, but when I do it the application crashed.

I tried to call at time only one class it works with the two I change the rank but the same problem the two classes are the same the only difference is that one with front camera and the other with the back one. This code is for the back camera it work correctly.

在此处输入图像描述

import 'dart:async';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mbd/camera/camT.dart';
import 'package:mbd/camera/cmaerabackT.dart';
import 'package:mbd/welcome_ecran.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
class back extends StatefulWidget {
  final CameraDescription camera;

  const back({
    Key key,
    @required this.camera,
  }) : super(key: key);
  @override
  _backState createState() => _backState();
}

class _backState extends State<back> {
  bool _cameraOn = true;


  Future<void> hello() async {
  //  WidgetsFlutterBinding.ensureInitialized();
    final cameras = await availableCameras();
    final b = 0;
    final firstCamera = cameras[0];
    final secondCamera = cameras[0];
    runApp(MaterialApp(
        theme: ThemeData.dark(),

        home: back(

          camera: firstCamera,
        )));
  }


  int a = 5;
  CameraController _controller;
  Future<void> _initializeControllerFuture;

  @override
  void initState()  {
    super.initState();
    _cameraOn=true;
    hello();
    SystemChrome.setEnabledSystemUIOverlays([]);

    _controller = CameraController(
      widget.camera,
      ResolutionPreset.ultraHigh,
    );
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    super.dispose();
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();

    _cameraOn;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          child: Column(children: <Widget>[
            Container(
              child:  FutureBuilder<void>(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    // If the Future is complete, display the preview.
                    return CameraPreview(_controller);
                  } else {
                    // Otherwise, display a loading indicator.
                    return Center(child: CircularProgressIndicator());
                  }
                },
              ),
              height: MediaQuery
                  .of(context)
                  .size
                  .height * 0.75,
            ),
            Container(height: 10),
            if (a == 5)
              Text(
                'La vue dans le viseur est-elle degage',
                style: TextStyle(fontSize: 20),
              ),
            if (a == 0) Text('essayer de prendre une photo'),
            Container(
              height: 25,
            ),
            if (a == 0)
              FloatingActionButton(
                child: Icon(Icons.camera_alt),
                // Provide an onPressed callback.
                onPressed: () async {
                  _cameraOn=false;
                  // Take the Picture in a try / catch block. If anything goes wrong,
                  // catch the error.
                  try {
                    // Ensure that the camera is initialized.
                    await _initializeControllerFuture;

                    // Construct the path where the image should be saved using the
                    // pattern package.
                    final path = join(
                      // Store the picture in the temp directory.
                      // Find the temp directory using the `path_provider` plugin.
                      (await getTemporaryDirectory()).path,
                      '${DateTime.now()}.png',
                    );

                    // Attempt to take a picture and log where it's been saved.
                    await _controller.takePicture(path);

                    // If the picture was taken, display it on a new screen.
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:( (context) => Display(imagePath: path)),
                      ),
                    );
                  } catch (e) {
                    // If an error occurs, log the error to the console.
                    print(e);
                  }
                },
              ),
            if (a == 5)
              Row(
                children: <Widget>[
                  Container(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width * 0.05,
                  ),
                  Container(
                      margin: const EdgeInsets.all(15.0),
                      padding: const EdgeInsets.all(3.0),
                      decoration: BoxDecoration(
                        border: Border.all(
                          width: 3.0,
                          color: Colors.lightBlueAccent,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                      ),
                      child: InkWell(
                        child: Text(
                          'NON',
                          style: TextStyle(fontSize: 20),
                        ),
                        onTap: null,
                      )),
                  Container(width: MediaQuery
                      .of(context)
                      .size
                      .width * 0.5),
                  Container(
                      margin: const EdgeInsets.all(15.0),
                      padding: const EdgeInsets.all(3.0),
                      decoration: BoxDecoration(
                        border: Border.all(
                          width: 3.0,
                          color: Colors.lightBlueAccent,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                      ),
                      child: InkWell(
                        child: Text(
                          'Oui',
                          style: TextStyle(fontSize: 20),
                        ),
                        onTap: () {
                          a = 0;
                          setState(() {
                            a = 0;
                          });
                          print('bonjoue$a');
                        },
                      )),
                ],
              ),
          ])),
    );
  }
}
class Display extends StatelessWidget {
  final String imagePath;

  const Display({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Display the Picture')),
        body: Container(
            child: Column(children: <Widget>[
              Container(
                  height: MediaQuery.of(context).size.height * 0.7,
                  child: Image.file(File(imagePath))),
              Container(
                height: 10,
              ),
              Text('La photo est-elle claire pas de pixels diffextuex truve'),
              Row(
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width * 0.05,
                  ),
                  Container(
                      margin: const EdgeInsets.all(15.0),
                      padding: const EdgeInsets.all(3.0),
                      decoration: BoxDecoration(
                        border: Border.all(
                          width: 3.0,
                          color: Colors.lightBlueAccent,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                      ),
                      child: InkWell(
                        child: Text(
                          'NON',
                          style: TextStyle(fontSize: 20),
                        ),
                        onTap: null,
                      )),
                  Container(width: MediaQuery.of(context).size.width * 0.5),
                  Container(
                      margin: const EdgeInsets.all(15.0),
                      padding: const EdgeInsets.all(3.0),
                      decoration: BoxDecoration(
                        border: Border.all(
                          width: 3.0,
                          color: Colors.lightBlueAccent,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                      ),
                      child: InkWell(
                        child: Text(
                          'Oui',
                          style: TextStyle(fontSize: 20),
                        ),
                        onTap: () {Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) =>Camera()),
                        );},
                      )),
                ],
              ),
            ])));
         }
           }

and this is the code of the front camera

import 'dart:async';
import 'dart:io';

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

import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';


Future<void> hello() async {
  //  WidgetsFlutterBinding.ensureInitialized();
  final cameras = await availableCameras();
  final b = 0;
  final sousou= cameras[1];

  runApp(MaterialApp(
      theme: ThemeData.dark(),

      home: Camera(

        camera: sousou,
      )));
}

// A screen that allows users to take a picture using a given camera.
class Camera extends StatefulWidget {
  final CameraDescription camera;

  const Camera({
    Key key,
    @required this.camera,
  }) : super(key: key);

  @override
  TakePictureScreenState createState() => TakePictureScreenState();
}

class TakePictureScreenState extends State<Camera> {

  int a = 5;
  CameraController _controller;
  Future<void> _initializeControllerFuture;
  @override
  void initState() {
    super.initState();
    print('bonjour');
    hello();
    SystemChrome.setEnabledSystemUIOverlays([]);

    _controller = CameraController(
      widget.camera,
      ResolutionPreset.high,
    );
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          child: Column(children: <Widget>[
        Container(
          child: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the Future is complete, display the preview.
                return CameraPreview(_controller);
              } else {
                // Otherwise, display a loading indicator.
                return Center(child: CircularProgressIndicator());
              }
            },
          ),
          height: MediaQuery.of(context).size.height * 0.75,
        ),
        Container(height: 10),
        if (a == 5)
          Text(
            'La vue dans le viseur est-elle degage',
            style: TextStyle(fontSize: 20),
          ),
        if (a == 0) Text('essayer de prendre une photo'),
        Container(
          height: 25,
        ),
        if (a == 0)
          FloatingActionButton(
            child: Icon(Icons.camera_alt),
            // Provide an onPressed callback.
            onPressed: () async {
              // Take the Picture in a try / catch block. If anything goes wrong,
              // catch the error.
              try {
                // Ensure that the camera is initialized.
                await _initializeControllerFuture;

                // Construct the path where the image should be saved using the
                // pattern package.
                final path = join(
                  // Store the picture in the temp directory.
                  // Find the temp directory using the `path_provider` plugin.
                  (await getTemporaryDirectory()).path,
                  '${DateTime.now()}.png',
                );

                // Attempt to take a picture and log where it's been saved.
                await _controller.takePicture(path);

                // If the picture was taken, display it on a new screen.
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DisplayPictureScreen(imagePath: path),
                  ),
                );
              } catch (e) {
                // If an error occurs, log the error to the console.
                print(e);
              }
            },
          ),
        if (a == 5)
          Row(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width * 0.05,
              ),
              Container(
                  margin: const EdgeInsets.all(15.0),
                  padding: const EdgeInsets.all(3.0),
                  decoration: BoxDecoration(
                    border: Border.all(
                      width: 3.0,
                      color: Colors.lightBlueAccent,
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                  ),
                  child: InkWell(
                    child: Text(
                      'NON',
                      style: TextStyle(fontSize: 20),
                    ),
                    onTap: null,
                  )),
              Container(width: MediaQuery.of(context).size.width * 0.5),
              Container(
                  margin: const EdgeInsets.all(15.0),
                  padding: const EdgeInsets.all(3.0),
                  decoration: BoxDecoration(
                    border: Border.all(
                      width: 3.0,
                      color: Colors.lightBlueAccent,
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                  ),
                  child: InkWell(
                    child: Text(
                      'Oui',
                      style: TextStyle(fontSize: 20),
                    ),
                    onTap: () {
                      a = 0;
                      setState(() {
                        a = 0;
                      });
                      print('bonjoue$a');
                    },
                  )),
            ],
          ),
      ])),
    );
  }
}

// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Display the Picture')),
        body: Container(
            child: Column(children: <Widget>[
          Container(
              height: MediaQuery.of(context).size.height * 0.7,
              child: Image.file(File(imagePath))),
          Container(
            height: 10,
          ),
          Text('La photo est-elle claire pas de pixels diffextuex truve'),
          Row(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width * 0.05,
              ),
              Container(
                  margin: const EdgeInsets.all(15.0),
                  padding: const EdgeInsets.all(3.0),
                  decoration: BoxDecoration(
                    border: Border.all(
                      width: 3.0,
                      color: Colors.lightBlueAccent,
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                  ),
                  child: InkWell(
                    child: Text(
                      'NON',
                      style: TextStyle(fontSize: 20),
                    ),
                    onTap: null,
                  )),
              Container(width: MediaQuery.of(context).size.width * 0.5),
              Container(
                  margin: const EdgeInsets.all(15.0),
                  padding: const EdgeInsets.all(3.0),
                  decoration: BoxDecoration(
                    border: Border.all(
                      width: 3.0,
                      color: Colors.lightBlueAccent,
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(
                            30.0) //                 <--- border radius here
                        ),
                  ),
                  child: InkWell(
                    child: Text(
                      'Oui',
                      style: TextStyle(fontSize: 20),
                    ),
                    onTap: () {
                      Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) =>back()),
                    );},
                  )),
            ],
          ),
        ])));
  }
}

and these are the errors which I found:

Repeating capture request cancelled.

E/BufferQueueProducer( 8606): [SurfaceTexture-1-8606-5] cancelBuffer: BufferQueue has been abandoned
I/chatty  ( 8606): uid=10176(com.example.phonizy2) Binder:8606_4 identical 11 lines
E/BufferQueueProducer( 8606): [SurfaceTexture-1-8606-5] cancelBuffer: BufferQueue has been abandoned
E/BufferQueueProducer( 8606): [SurfaceTexture-1-8606-5] connect: BufferQueue has been abandoned
E/BufferQueueProducer( 8606): [SurfaceTexture-1-8606-5] setMaxDequeuedBufferCount: BufferQueue has been abandoned
V/SensorManager( 8606): RegisterListener LIS3DH Accelerometer type:1 delay:200000us by android.view.OrientationEventListener$SensorEventListenerImpl
E/Parcel  ( 8606): Reading a NULL string not supported here.
E/libc    ( 8606): Access denied finding property "persist.camera.privapp.list"
I/CameraManager( 8606): Using legacy camera HAL.
D/Camera  ( 8606): mHypnusCtrl is true
E/libc    ( 8606): Access denied finding property "camera.hal1.packagelist"
E/CheckPermission( 8606): camera-code= 5
V/SensorManager( 8606): unRegisterListener by android.view.OrientationEventListener$SensorEventListenerImpl
E/Parcel  ( 8606): Reading a NULL string not supported here.
D/AndroidRuntime( 8606): Shutting down VM
E/AndroidRuntime( 8606): FATAL EXCEPTION: main
E/AndroidRuntime( 8606): Process: com.example.phonizy2, PID: 8606
E/AndroidRuntime( 8606): java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Surface android.media.ImageReader.getSurface()' on a null object reference
E/AndroidRuntime( 8606):    at io.flutter.plugins.camera.Camera.startPreview(Camera.java:424)
E/AndroidRuntime( 8606):    at io.flutter.plugins.camera.Camera$2.onOpened(Camera.java:160)
E/AndroidRuntime( 8606):    at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:143)
E/AndroidRuntime( 8606):    at android.os.Handler.handleCallback(Handler.java:790)
E/AndroidRuntime( 8606):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 8606):    at android.os.Looper.loop(Looper.java:198)
E/AndroidRuntime( 8606):    at android.app.ActivityThread.main(ActivityThread.java:7055)
E/AndroidRuntime( 8606):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 8606):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
E/AndroidRuntime( 8606):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
I/Process ( 8606): Sending signal. PID: 8606 SIG: 9

The issue seems to happen only on some devices. There's a GitHub issue ticket regarding the same behavior and the fix should have been published by the end of 2020. I suggest try using the latest version of the camera plugin and see if the same issue persists. I've tried using the sample code provided and it works well on my device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM