Skip to content

Instantly share code, notes, and snippets.

@feliperyan
Last active August 1, 2024 04:07
Show Gist options
  • Save feliperyan/9ef5da09baea3296a590d9329ba349b4 to your computer and use it in GitHub Desktop.
Save feliperyan/9ef5da09baea3296a590d9329ba349b4 to your computer and use it in GitHub Desktop.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
/// CameraApp is the Main Application.
class CameraView extends StatefulWidget {
/// Default Constructor
const CameraView({super.key});
@override
State<CameraView> createState() => _CameraViewState();
}
class _CameraViewState extends State<CameraView> {
late CameraController controller;
bool isInited = false;
XFile? picture;
@override
void initState() {
super.initState();
List<CameraDescription> cameras;
availableCameras().then((List<CameraDescription> onValue) {
cameras = onValue;
controller = CameraController(cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
isInited = true;
}).catchError((Object e) {
if (e is CameraException) {
switch (e.code) {
case 'CameraAccessDenied':
// Handle access errors here.
break;
default:
// Handle other errors here.
break;
}
}
});
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (!isInited) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (!controller.value.isInitialized) {
return Container();
}
return Scaffold(
appBar: AppBar(title: const Text('Camera View')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 300,
height: 260,
child: CameraPreview(controller),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: onTakePictureButtonPress,
// onPressed: () => {},
child: const Text('Capture'),
)
],
)));
}
void onTakePictureButtonPress() {
takePicture().then((XFile? file) {
print('onTakePictureButtonPress triggered');
if (mounted) {
setState(() {
picture = file;
});
print('file saved to ${file?.path}');
file?.saveTo('/home/felipe').then((_) {
file.length().then((val) {
print('size: ${val / 0.001}');
});
});
}
});
}
Future<XFile?> takePicture() async {
if (!controller.value.isInitialized) {
print('cant take picture, controller not inited');
return null;
}
try {
final XFile file = await controller.takePicture();
return file;
} on CameraException catch (e) {
print('error on controller.takePicture() was: ${e.code}');
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment