Трепетание приложения зависало при смене камеры - PullRequest
0 голосов
/ 22 апреля 2020

[это снимок экрана somr enter image description here Я пытаюсь написать приложение для флаттера, чтобы проверить переднюю и заднюю камеру при первом открытии задней камеры пользователем, будет отображаться вопрос, если изображение ясно после того, как он сделает снимок, после того, как его спросят, если фотография четкая, я поменяю камеру, но когда я делаю это, приложение разбилось, я попытался вызвать только один класс, который работает с двумя, я меняю ранк но та же проблема, что два предложения одинаковы, единственное отличие состоит в том, что один с передней камерой, а другой с задней, этот код предназначен для задней камеры, он корректно работает import 'dart: asyn c'; 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()),
                        );},
                      )),
                ],
              ),
            ])));
         }
           }
a

и это код передней камеры

          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()),
                    );},
                  )),
            ],
          ),
        ])));
  }
}

, и это ошибка, которую я обнаружил и благодаря которой повторение запроса на захват отменено.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...