mobile_scanner.dart
2.69 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'mobile_scanner_arguments.dart';
enum Ratio {
ratio_4_3,
ratio_16_9
}
/// A widget showing a live camera preview.
class MobileScanner extends StatefulWidget {
/// The controller of the camera.
final MobileScannerController? controller;
final Function(Barcode barcode, MobileScannerArguments args)? onDetect;
final BoxFit fit;
/// Create a [MobileScanner] with a [controller], the [controller] must has been initialized.
const MobileScanner(
{Key? key, this.onDetect, this.controller, this.fit = BoxFit.cover})
: assert((controller != null )), super(key: key);
@override
State<MobileScanner> createState() => _MobileScannerState();
}
class _MobileScannerState extends State<MobileScanner>
with WidgetsBindingObserver {
bool onScreen = true;
late MobileScannerController controller;
@override
void initState() {
super.initState();
if (widget.controller == null) {
controller = MobileScannerController();
} else {
controller = widget.controller!;
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
setState(() => onScreen = true);
} else {
if (onScreen) {
controller.stop();
}
setState(() {
onScreen = false;
});
}
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, BoxConstraints constraints) {
if (!onScreen) return const Text("Camera Paused.");
return ValueListenableBuilder(
valueListenable: controller.args,
builder: (context, value, child) {
value = value as MobileScannerArguments?;
if (value == null) {
return Container(color: Colors.black);
} else {
controller.barcodes.listen(
(a) => widget.onDetect!(a, value as MobileScannerArguments));
debugPrint(' size MediaQuery ${MediaQuery.of(context).size}');
return ClipRect(
child: SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: FittedBox(
fit: widget.fit,
child: SizedBox(
width: value.size.width,
height: value.size.height,
child: Texture(textureId: value.textureId),
),
),
),
);
}
});
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}