抖动:切换相机不起作用

时间:2018-08-12 15:36:39

标签: android dart flutter

我无法切换相机。有人可以帮我吗? 正在进行“ onPressed:()=> _cameraSwitcher()”调用,但仍然出现错误。

I/flutter (19390): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (19390): The method 'toggleCamera' was called on null.
I/flutter (19390): Receiver: null

下面是详细代码。

util.dart

import "dart:async";
import "package:flutter/material.dart";
import "package:camera/camera.dart";

class CameraWidget extends StatefulWidget {
  static CameraWidgetState of(BuildContext context) =>
      context.ancestorStateOfType(const TypeMatcher<CameraWidgetState>());

  @override
  CameraWidgetState createState() => CameraWidgetState();

}

class CameraWidgetState extends State<CameraWidget> {
  List<CameraDescription> cameras;
  CameraController controller;
  bool isReady= false;
  int selectedCamera = 1;
  bool noCameraDevice = false;

  @override
  void initState() {
    super.initState();
    _setupCamera();
  }

  Future<void> _setupCamera() async {
    try {
      // initialize cameras.
      cameras = await availableCameras();
      // initialize camera controllers.
      controller = new CameraController(
          cameras[selectedCamera], ResolutionPreset.medium
      );
      await controller.initialize();
    } on CameraException catch (_) {
      //debugPrint("Some error occured!").
    }
    if (!mounted) return;
    setState(() {
      isReady = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (controller == null || !controller.value.isInitialized) {
      return new Container();
    }
    return new AspectRatio(
        aspectRatio: controller.value.aspectRatio,
        child: new CameraPreview(controller));
  }

  void toggleCamera(){
    setState(() {
      selectedCamera= (selectedCamera==1)? 0: 1;
    });
  }
}

mirror.dart

    //import "dart:async";
import "package:flutter/material.dart";
import "../core/util.dart";

class MirrorApp extends StatefulWidget {
  @override
  _MirrorAppState createState() => _MirrorAppState();
}

class _MirrorAppState extends State<MirrorApp> {
  GlobalKey<CameraWidgetState> _cameraWidgetStateKey = new GlobalKey<CameraWidgetState>();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text("Will show ads here"),
        backgroundColor: Colors.blue
      ),
      body: new Stack(
        children: <Widget>[
          new Center(
            child: new CameraWidget(),
          ),
          new Row(
            children: <Widget>[
              new IconButton(
                  icon: new Icon(Icons.camera_front),
                  onPressed: () => _cameraSwitcher()
              ),
              new IconButton(
                  icon: new Icon(Icons.photo_camera),
                  onPressed: () => _photoClicked()
              ),
              new IconButton(
                  icon: new Icon(Icons.photo),
                  onPressed: () => _photoGallery()
              ),
              new IconButton(
                  icon: new Icon(Icons.share),
                  onPressed: () => _shareOnSocialMedia()
              )
            ],
          )
        ],
      ),
    );
  }

  _cameraSwitcher() {
    debugPrint("Clicked Toggle camera!!");
//    int selectedCamera = _cameraWidgetStateKey.currentState.selectedCamera;
    _cameraWidgetStateKey.currentState.toggleCamera();// = 0; //   toggleCamera();
  }

  _photoClicked() { return debugPrint("Photo clicked!!");}

  _photoGallery() { return debugPrint("Open Photo gallery!!");}

  _shareOnSocialMedia() { return debugPrint("Share on social media");}

}

编辑1- 在遵循Yamin的建议之后,我必须更新如下的toggleCamera方法以实际切换相机。

void toggleCamera(){
    setState(() {
      debugPrint("toggler called $selectedCamera");
      selectedCamera= (selectedCamera==1)? 0: 1;
      debugPrint("toggler called $selectedCamera");
      _setupCamera();
    });
  }

但是我想知道这是否正确吗?我的印象是,如果我将更新selectedCamera变量,它足以重建Camera小部件。这是由于未来的目标吗?

1 个答案:

答案 0 :(得分:1)

globalKey已创建,但未分配给窗口小部件。因此,当您调用它时它为空:

在util.dart中

class CameraWidget extends StatefulWidget {
  static CameraWidgetState of(BuildContext context) =>
      context.ancestorStateOfType(const TypeMatcher<CameraWidgetState>());
  CameraWidget({Key key}) : super(key: key); //This line is added


  @override
  CameraWidgetState createState() => CameraWidgetState();

}

在mirror.dart第29行中:

body: new Stack(
    children: <Widget>[
      new Center(
        child: new CameraWidget(
          key: _cameraWidgetStateKey, //this line is added
        ),
      ),

最好检查globalKey docsthis question

更新:据我所知,更新后的代码没有任何问题,如果它可以正常工作,那就很好。