camera_view.dart
1.94 KB
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
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'camera_args.dart';
/// A widget showing a live camera preview.
class CameraView extends StatefulWidget {
/// The controller of the camera.
final CameraController? controller;
final Function(Barcode barcode, CameraArgs args)? onDetect;
/// Create a [CameraView] with a [controller], the [controller] must has been initialized.
const CameraView({Key? key, this.onDetect, this.controller}) : super(key: key);
@override
State<CameraView> createState() => _CameraViewState();
}
class _CameraViewState extends State<CameraView> {
late CameraController controller;
@override
initState() {
super.initState();
controller = widget.controller ?? CameraController();
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: controller.args,
builder: (context, value, child) {
value = value as CameraArgs?;
if (value == null) {
return Container(color: Colors.black);
} else {
controller.barcodes
.listen((a) => widget.onDetect!(a, value as CameraArgs));
return ClipRect(
child: Transform.scale(
scale: value.size.fill(MediaQuery.of(context).size),
child: Center(
child: AspectRatio(
aspectRatio: value.size.aspectRatio,
child: Texture(textureId: value.textureId),
),
),
),
);
}
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
extension on Size {
double fill(Size targetSize) {
if (targetSize.aspectRatio < aspectRatio) {
return targetSize.height * aspectRatio / targetSize.width;
} else {
return targetSize.width / aspectRatio / targetSize.height;
}
}
}