NoSuchMethodError:在空值上调用了吸气剂“名称”

时间:2020-10-26 19:31:58

标签: flutter dart

我正在尝试添加一个选项来拍摄图像和图片并将其保存到本地设备。我设法添加了摄像机和视频。每当我单击“拍照”或“视频”按钮时,我都会收到错误消息

I / flutter(4827):NoSuchMethodError:调用了吸气剂“名称” 空值。接收者:null。 呼叫:姓名。 NoSuchMethodError:获取器“名称” 被调用为null。接收方:空尝试呼叫:名称

我使用flutter camera library。我究竟做错了什么?预先谢谢你

我的相机代码

List<CameraDescription> cameras = [];

void logError(String code, String message) =>
    print('Error: $code\nError Message: $message');

Future<void> main() async {
  // Fetch the available cameras before initializing the app.
  try {
    WidgetsFlutterBinding.ensureInitialized();
    cameras = await availableCameras();
  } on CameraException catch (e) {
    logError(e.code, e.description);
  }
  final camera = cameras.first;
  runApp(TakePicturePage(camera: camera));

}

class TakePicturePage extends StatefulWidget {
  final CameraDescription camera;
  TakePicturePage({@required this.camera});

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

class _TakePicturePageState extends State<TakePicturePage> {
  final fileName = DateTime.now().millisecondsSinceEpoch.toString();
  var vidPath;
  CameraController _cameraController;
  Future<void> _initializeCameraControllerFuture;
  int _selectedIndex = 0;
  bool _start = false;
  bool _isRec = false;
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
      if (_selectedIndex == 1) {
        _start = !_start;
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _initApp();
    _cameraController =
        CameraController(widget.camera, ResolutionPreset.medium);

    _initializeCameraControllerFuture = _cameraController.initialize();
    _fileInit();
  }

  _initApp() async {
    final cameras = await availableCameras();
    final camera = cameras.first;

    _cameraController = CameraController(
      camera, ResolutionPreset.max,
    );
  }

  void _fileInit() async {
    vidPath = join((await getTemporaryDirectory()).path, '${fileName}.mp4');
  }

  void _takePicture(BuildContext context) async {
    try {
      await _initializeCameraControllerFuture;

      if (_selectedIndex == 0) {
        final imgPath =
        join((await getTemporaryDirectory()).path, '${fileName}.png');
        await _cameraController.takePicture(imgPath);
        Navigator.pop(context, imgPath);
      } else {
        if (_start) {
          await _cameraController.startVideoRecording(vidPath);
          setState(() {
            _start = !_start;
            _isRec = !_isRec;
          });
        } else {
          _cameraController.stopVideoRecording();
          setState(() {
            _isRec = !_isRec;
          });
          Navigator.pop(context, vidPath);
        }
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          FutureBuilder(
            future: _initializeCameraControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return CameraPreview(_cameraController);
              } else {
                return Center(child: CircularProgressIndicator(backgroundColor: Colors.green,));
              }
            },
          ),
          SafeArea(
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: FloatingActionButton(
                  backgroundColor: Colors.green,
                  child:   _selectedIndex == 1 ? _isRec == true?Icon(Icons.pause, color: Colors.white):Icon(Icons.play_arrow, color: Colors.white) : Icon(Icons.camera, color: Colors.white),
                  onPressed: () {
                    _takePicture(context);
                  },
                ),
              ),
            ),
          ),
          _isRec == true
              ? SafeArea(
            child: Container(
              height: 30,
              // alignment: Alignment.topLeft,
              decoration: BoxDecoration(
                color: Color(0xFFEE4400),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  "REC",
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                      color: Color(0xFFFAFAFA)),
                ),
              ),
            ),
          )
              : SizedBox(
            height: 0,
          )
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.camera),
            title: Text('Picture'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.videocam),
            title: Text('Video'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.green,
        onTap: _onItemTapped,
      ),
    );
  }

  @override
  void dispose() {
    _cameraController.dispose();
    super.dispose();
  }
}

相机没有打开

enter image description here

0 个答案:

没有答案