camera_view.dart
1.51 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
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'camera_args.dart';
import 'camera_controller.dart';
/// A widget showing a live camera preview.
class CameraView extends StatelessWidget {
/// 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.
CameraView(this.controller, {this.onDetect});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: controller.args,
builder: (context, value, child) => _build(context, value as CameraArgs?),
);
}
Widget _build(BuildContext context, CameraArgs? value) {
if (value == null) {
return Container(color: Colors.black);
} else {
controller.barcodes.listen((a) => onDetect!(a, value));
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),
),
),
),
);
}
}
}
extension on Size {
double fill(Size targetSize) {
if (targetSize.aspectRatio < aspectRatio) {
return targetSize.height * aspectRatio / targetSize.width;
} else {
return targetSize.width / aspectRatio / targetSize.height;
}
}
}