颤振无法打开闪光灯

时间:2020-05-20 13:11:25

标签: flutter dart

我正在尝试编写一个抖动应用程序,在该应用程序中,我打开照相机,向用户询问一个问题:当用户按下按钮应打开闪光灯时,会显示照相机浮动操作按钮,但有例外。那是我使用波动camera软件包和Lamp的代码:

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:lamp/lamp.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

import 'package:backback/Resultat/testclass.dart' as globals;

import 'package:backback/Camera/camerafrontT.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

import 'displaybackT.dart';
void main()=> runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Selectable GridView',
      theme: ThemeData(
        brightness: Brightness.dark,
      ),

      home:CameraScreen(),
    );
  }
}
class CameraScreen extends StatefulWidget {
  @override
  _CameraScreenState createState() {
    return _CameraScreenState();
  }
}

class _CameraScreenState extends State {
  bool _hasFlash = false;
  bool _isOn = false;
  double _intensity = 1.0;
  initPlatformState() async {
    bool hasFlash = await Lamp.hasLamp;
    print("Device has flash ? $hasFlash");
    setState(() { _hasFlash = hasFlash; });
  }

  int a = 5;

  CameraController controller;
  List cameras;
  int selectedCameraIdx;
  String imagePath;

  Future _turnFlash() async {
    _intensityChanged(5.0);
    _isOn ? Lamp.turnOff() : Lamp.turnOn(intensity: _intensity);    var f = await Lamp.hasLamp;
    setState((){
      _hasFlash = f;
      _isOn = !_isOn;
    });
  }
  _intensityChanged(double intensity) {
    Lamp.turnOn(intensity : intensity);
    setState((){
      _intensity = intensity;
    });
  }

  @override
  void initState() {
    super.initState();
   initPlatformState();

    availableCameras().then((availableCameras) {
      cameras = availableCameras;

      if (cameras.length > 0) {
        setState(() {
          selectedCameraIdx = 0;
        });

        _initCameraController(cameras[selectedCameraIdx]).then((void v) {});
      } else {
        print("No camera available");
      }
    }).catchError((err) {
      print('Error: $err.code\nError Message: $err.message');
    });

  }


  Future _initCameraController(CameraDescription cameraDescription) async {
    if (controller != null) {
      await controller.dispose();
    }

    controller = CameraController(cameraDescription, ResolutionPreset.high);

    // If the controller is updated then update the UI.
    controller.addListener(() {
      if (mounted) {
        setState(() {});
      }

      if (controller.value.hasError) {
        print('Camera error ${controller.value.errorDescription}');
      }
    });

    try {
      await controller.initialize();
    } on CameraException catch (e) {
      _showCameraException(e);
    }

    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
     home: Scaffold(
      appBar: AppBar(
        title: const Text('Click To Share'),
        backgroundColor: Colors.blueGrey,
      ),
      body: Container(
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: _cameraPreviewWidget(),
              ),
              SizedBox(height: 10.0),
              if (a == 5)
                Text(
                  'La vue dans le viseur est-elle degage',
                  style: TextStyle(fontSize: 20),textAlign: TextAlign.center,
                ),

              if (a == 0) Text('essayer de prendre une photo',textAlign: TextAlign.center,),
              Container(
                height: 25,
              ),
              if (a == 0)
                FloatingActionButton(
                    child: Icon(Icons.camera_alt),
                    // Provide an onPressed callback.
                    onPressed: () {
_turnFlash();
                      //_onCapturePressed(context);
                    }),
              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:(){
                            globals.Data.etatcameraback('0');
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => CameraScreen2()),
                            );
                          },
                        )),
                    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;

                            });

                          },
                        )),
                  ],
                ),
              SizedBox(height: 20.0)
            ],
          ),
        ),
      ),
    ));
  }

  /// Display Camera preview.
  Widget _cameraPreviewWidget() {
    if (controller == null || !controller.value.isInitialized) {
      return const Text(
        'Loading',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20.0,
          fontWeight: FontWeight.w900,
        ),
      );
    }

    return AspectRatio(
      aspectRatio: controller.value.aspectRatio,
      child: CameraPreview(controller),
    );
  }

  /// Display the control bar with buttons to take pictures
  Widget _captureControlRowWidget(context) {
    return Expanded(
      child: Align(
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.max,
          children: [
            FloatingActionButton(
                child: Icon(Icons.camera),
                backgroundColor: Colors.blueGrey,
                onPressed: () {
                  _onCapturePressed(context);
                })
          ],
        ),
      ),
    );
  }



void _onCapturePressed(context) async {
    // Take the Picture in a try / catch block. If anything goes wrong,
    // catch the error.
    try {
      // Attempt to take a picture and log where it's been saved
      final path = join(
        // In this example, store the picture in the temp directory. Find
        // the temp directory using the `path_provider` plugin.
        (await getTemporaryDirectory()).path,
        '${DateTime.now()}.png',
      );
      print(path);
      await controller.takePicture(path);

      // If the picture was taken, display it on a new screen
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PreviewImageScreen(imagePath: path),
        ),
      );
    } catch (e) {
      // If an error occurs, log the error to the console.
      print(e);
    }
  }

  void _showCameraException(CameraException e) {
    String errorText = 'Error: ${e.code}\nError Message: ${e.description}';
    print(errorText);

    print('Error: ${e.code}\n${e.description}');
  }


}

该应用程序正常运行。我按下按钮以运行闪光灯,但有一个由闪动引起的异常,但闪光灯没有打开

  E/MethodChannel#github.com/clovisnicolas/flutter_lamp( 4197):     at android.app.ActivityThread.main(ActivityThread.java:7055)
    E/MethodChannel#github.com/clovisnicolas/flutter_lamp( 4197):   at java.lang.reflect.Method.invoke(Native Method)
    E/MethodChannel#github.com/clovisnicolas/flutter_lamp( 4197):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
    E/MethodChannel#github.com/clovisnicolas/flutter_lamp( 4197):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
    E/flutter ( 4197): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception:

 

PlatformException(error, getParameters failed (empty parameters), null)

我需要一些帮助来解决我的问题。我看上去很长,但是没有发现任何有趣的结果。

0 个答案:

没有答案