1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
| import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final cameras = await availableCameras();
runApp(MaterialApp(home: CameraScreen(cameras: cameras)));
}
class CameraScreen extends StatefulWidget {
final List<CameraDescription> cameras;
const CameraScreen({super.key, required this.cameras});
@override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen>
with WidgetsBindingObserver {
CameraController? _controller;
int _cameraIndex = 0;
FlashMode _flashMode = FlashMode.auto;
bool _isCapturing = false;
final List<String> _capturedPaths = [];
String? _initError;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_initCamera();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller?.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final ctrl = _controller;
if (ctrl == null || !ctrl.value.isInitialized) return;
if (state == AppLifecycleState.inactive) {
ctrl.dispose();
} else if (state == AppLifecycleState.resumed) {
_initCamera();
}
}
Future<void> _initCamera() async {
if (widget.cameras.isEmpty) {
setState(() => _initError = 'No cameras found on this device.');
return;
}
final camera = widget.cameras[_cameraIndex];
final ctrl = CameraController(
camera,
ResolutionPreset.high,
enableAudio: false,
imageFormatGroup: ImageFormatGroup.jpeg,
);
try {
await ctrl.initialize();
await ctrl.setFlashMode(_flashMode);
if (!mounted) return;
setState(() { _controller = ctrl; _initError = null; });
} on CameraException catch (e) {
setState(() => _initError = '${e.code}: ${e.description}');
}
}
Future<void> _switchCamera() async {
if (widget.cameras.length < 2) return;
await _controller?.dispose();
setState(() { _cameraIndex = (_cameraIndex + 1) % widget.cameras.length; _controller = null; });
await _initCamera();
}
Future<void> _cycleFlash() async {
final modes = [FlashMode.auto, FlashMode.always, FlashMode.off, FlashMode.torch];
final next = modes[(modes.indexOf(_flashMode) + 1) % modes.length];
await _controller?.setFlashMode(next);
setState(() => _flashMode = next);
}
Future<void> _takePicture() async {
final ctrl = _controller;
if (ctrl == null || !ctrl.value.isInitialized || _isCapturing) return;
setState(() => _isCapturing = true);
try {
final dir = await getTemporaryDirectory();
final path = p.join(dir.path, '${DateTime.now().millisecondsSinceEpoch}.jpg');
final file = await ctrl.takePicture();
await File(file.path).copy(path);
setState(() => _capturedPaths.insert(0, path));
} on CameraException catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Capture error: ${e.description}')),
);
}
} finally {
setState(() => _isCapturing = false);
}
}
IconData get _flashIcon => switch (_flashMode) {
FlashMode.auto => Icons.flash_auto,
FlashMode.always => Icons.flash_on,
FlashMode.off => Icons.flash_off,
FlashMode.torch => Icons.highlight,
_ => Icons.flash_auto,
};
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Column(
children: [
_TopBar(
flashIcon: _flashIcon,
onFlash: _cycleFlash,
canSwitch: widget.cameras.length > 1,
onSwitch: _switchCamera,
),
Expanded(child: _buildPreview()),
_BottomControls(
isCapturing: _isCapturing,
onCapture: _takePicture,
lastCapturePath: _capturedPaths.isNotEmpty ? _capturedPaths.first : null,
onShowGallery: _capturedPaths.isEmpty ? null : () => _showGallery(context),
),
],
),
),
);
}
Widget _buildPreview() {
if (_initError != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(_initError!, style: const TextStyle(color: Colors.red), textAlign: TextAlign.center),
),
);
}
final ctrl = _controller;
if (ctrl == null || !ctrl.value.isInitialized) {
return const Center(child: CircularProgressIndicator(color: Colors.white));
}
return ClipRect(
child: OverflowBox(
alignment: Alignment.center,
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: ctrl.value.previewSize?.height ?? 1,
height: ctrl.value.previewSize?.width ?? 1,
child: CameraPreview(ctrl),
),
),
),
);
}
void _showGallery(BuildContext context) {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => _GalleryScreen(paths: List.from(_capturedPaths)),
));
}
}
class _TopBar extends StatelessWidget {
final IconData flashIcon;
final VoidCallback onFlash;
final bool canSwitch;
final VoidCallback onSwitch;
const _TopBar({required this.flashIcon, required this.onFlash, required this.canSwitch, required this.onSwitch});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(icon: Icon(flashIcon, color: Colors.white), onPressed: onFlash, tooltip: 'Toggle flash'),
if (canSwitch)
IconButton(icon: const Icon(Icons.flip_camera_ios, color: Colors.white), onPressed: onSwitch, tooltip: 'Switch camera'),
],
),
);
}
}
class _BottomControls extends StatelessWidget {
final bool isCapturing;
final VoidCallback onCapture;
final String? lastCapturePath;
final VoidCallback? onShowGallery;
const _BottomControls({required this.isCapturing, required this.onCapture, this.lastCapturePath, this.onShowGallery});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
GestureDetector(
onTap: onShowGallery,
child: Container(
width: 56, height: 56,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.white54),
color: Colors.white12,
),
child: lastCapturePath != null
? ClipRRect(borderRadius: BorderRadius.circular(7), child: Image.file(File(lastCapturePath!), fit: BoxFit.cover))
: const Icon(Icons.photo_library, color: Colors.white54),
),
),
GestureDetector(
onTap: isCapturing ? null : onCapture,
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
width: isCapturing ? 64 : 72, height: isCapturing ? 64 : 72,
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white, border: Border.all(color: Colors.white54, width: 4)),
child: isCapturing ? const Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator(strokeWidth: 2)) : const SizedBox.shrink(),
),
),
const SizedBox(width: 56),
],
),
);
}
}
class _GalleryScreen extends StatefulWidget {
final List<String> paths;
const _GalleryScreen({required this.paths});
@override
State<_GalleryScreen> createState() => _GalleryScreenState();
}
class _GalleryScreenState extends State<_GalleryScreen> {
late final List<String> _paths = List.from(widget.paths);
void _delete(String path) {
File(path).deleteSync();
setState(() => _paths.remove(path));
if (_paths.isEmpty && mounted) Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Gallery (${_paths.length})'), backgroundColor: Colors.black, foregroundColor: Colors.white),
backgroundColor: Colors.black,
body: GridView.builder(
padding: const EdgeInsets.all(4),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, crossAxisSpacing: 4, mainAxisSpacing: 4),
itemCount: _paths.length,
itemBuilder: (_, i) {
final path = _paths[i];
return GestureDetector(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => _PhotoViewer(path: path, onDelete: () => _delete(path)),
)),
child: Image.file(File(path), fit: BoxFit.cover),
);
},
),
);
}
}
class _PhotoViewer extends StatelessWidget {
final String path;
final VoidCallback onDelete;
const _PhotoViewer({required this.path, required this.onDelete});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black, foregroundColor: Colors.white,
actions: [
IconButton(icon: const Icon(Icons.delete, color: Colors.red), onPressed: () { onDelete(); Navigator.of(context).pop(); }),
],
),
body: Center(child: Image.file(File(path))),
);
}
}
|