Files
SDKmuta/lib/screens/camera_screen.dart
T
2025-04-05 11:47:40 +02:00

324 lines
9.7 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart';
import 'yolo_detector.dart';
import 'preview_screen.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key});
@override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
CameraController? _controller;
Future<void>? _initializeControllerFuture;
late YOLODetector _yoloDetector;
Color _bulletColor = Colors.blue; // default fallback
// The variable to hold the number of bullets entered by the user (default set to 5)
int _numberOfBullets = 5;
@override
void initState() {
super.initState();
_loadBulletCount();
_initCamera();
_loadBulletColor(); // 👈
YOLODetector.create().then((detector) => _yoloDetector = detector);
}
Future<void> _loadBulletColor() async {
final prefs = await SharedPreferences.getInstance();
final selected = prefs.getString('bulletColor') ?? 'Blue';
setState(() {
_bulletColor = _getColorFromName(selected);
});
}
Color _getColorFromName(String colorName) {
switch (colorName.toLowerCase()) {
case 'blue':
return Colors.blue;
case 'green':
return Colors.green;
case 'yellow':
return Colors.yellow;
case 'purple':
return Colors.purple;
case 'cyan':
return Colors.cyan;
case 'teal':
return Colors.teal;
case 'indigo':
return Colors.indigo;
case 'pink':
return Colors.pink;
case 'lime':
return Colors.lime;
case 'mint':
return Colors.greenAccent;
case 'sky':
return Colors.lightBlueAccent;
case 'violet':
return Colors.deepPurpleAccent;
default:
return Colors.blue;
}
}
Future<void> _loadBulletCount() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_numberOfBullets = prefs.getInt('bulletCount') ?? 5; // Load stored bullet count, default to 5
});
}
Future<void> _saveBulletCount(int count) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('bulletCount', count); // Save the bullet count
}
Future<void> _initCamera() async {
final cameras = await availableCameras();
final camera = cameras.first;
_controller = CameraController(
camera,
ResolutionPreset.high,
enableAudio: false,
);
_initializeControllerFuture = _controller!.initialize();
if (mounted) setState(() {});
}
@override
void dispose() {
_controller?.dispose();
_yoloDetector.close();
super.dispose();
}
Future<void> _takePicture() async {
try {
await _initializeControllerFuture;
final file = await _controller!.takePicture();
final imageFile = File(file.path);
final imageBytes = await imageFile.readAsBytes();
final decodedImage = img.decodeImage(imageBytes)!;
// Crop center square from full image
final width = decodedImage.width;
final height = decodedImage.height;
final size = width < height ? width : height;
final offsetX = (width - size) ~/ 2;
final offsetY = (height - size) ~/ 2;
final cropped = img.copyCrop(
decodedImage,
x: offsetX,
y: offsetY,
width: size,
height: size,
);
final croppedFile = File('${file.path}_square.jpg')
..writeAsBytesSync(img.encodeJpg(cropped));
final detections = await _yoloDetector.detect(croppedFile);
if (!mounted) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PreviewScreen(
imagePath: croppedFile.path,
detections: detections,
bulletCount: _numberOfBullets, // Pass the bullet count
),
),
);
} catch (e) {
print('Error taking picture: $e');
}
}
// Method to show the dialog for selecting the number of bullets
void _showBulletDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
backgroundColor: Colors.grey[900],
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(24.0), // Increased padding for better spacing
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(bottom: 16.0),
child: Text(
'Select the number of bullets',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Center(
child: Wrap(
alignment: WrapAlignment.center,
spacing: 12,
runSpacing: 12,
children: List.generate(5, (index) {
final bulletNum = index + 1;
final isSelected = _numberOfBullets == bulletNum;
return ElevatedButton(
onPressed: () {
_selectBulletCount(bulletNum);
Navigator.of(context).pop();
},
style: ElevatedButton.styleFrom(
backgroundColor:
isSelected ? _bulletColor : Colors.grey[800],
foregroundColor: Colors.white,
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: Text(
'$bulletNum',
style: TextStyle(
fontSize: 18,
fontWeight:
isSelected ? FontWeight.bold : FontWeight.normal,
),
),
);
}),
),
),
],
),
),
);
},
);
}
// Update the bullet count and save it
void _selectBulletCount(int number) {
setState(() {
_numberOfBullets = number; // Update the selected number
});
_saveBulletCount(number); // Save the selected number
}
@override
Widget build(BuildContext context) {
if (_controller == null || _initializeControllerFuture == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
extendBody: true,
appBar: AppBar(
backgroundColor: Colors.grey[900],
title: const Text(
"Align the target inside the square",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
centerTitle: true,
actions: [
// Display the selected bullet count
IconButton(
icon: Text(
'$_numberOfBullets',
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
onPressed: _showBulletDialog, // Show dialog on tap
),
const SizedBox(width: 16), // Space after the number
],
),
bottomNavigationBar: BottomAppBar(
color: Colors.grey[900],
shape: const CircularNotchedRectangle(),
notchMargin: 8.0,
child: SizedBox(height: 60),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: _takePicture,
child: const Icon(Icons.camera_alt, color: Colors.black),
),
body: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final screenSize = MediaQuery.of(context).size;
return Stack(
children: [
Positioned.fill(
child: Container(
color: Colors.black, // covers any empty space
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize!.height,
height: _controller!.value.previewSize!.width,
child: CameraPreview(_controller!),
),
),
),
),
Center(
child: Container(
width: screenSize.width * 0.9,
height: screenSize.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
color: _bulletColor.withOpacity(0.9),
width: 3,
),
),
),
),
],
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
);
}
}