Flutter笔记:使用相机
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController _controller;
CameraLensDirection _direction = CameraLensDirection.back;
@override
void initState() {
super.initState();
_initCameraController();
}
void _initCameraController() async {
final cameras = await availableCameras();
final firstCamera = cameras.firstWhere(
(camera) => camera.lensDirection == _direction,
);
_controller = CameraController(
firstCamera,
ResolutionPreset.medium,
);
await _controller.initialize();
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (!_controller.value.isInitialized) {
return Container();
}
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: CameraPreview(_controller),
);
}
}
这段代码展示了如何在Flutter中使用camera插件来初始化一个相机并显示预览。它首先检查并初始化了相机,然后在界面上展示了相机预览。这是学习如何在Flutter应用中集成相机功能的一个很好的起点。
评论已关闭