mobile_scanner.dart
10.8 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/src/mobile_scanner_controller.dart';
import 'package:mobile_scanner/src/mobile_scanner_exception.dart';
import 'package:mobile_scanner/src/mobile_scanner_platform_interface.dart';
import 'package:mobile_scanner/src/objects/barcode_capture.dart';
import 'package:mobile_scanner/src/objects/mobile_scanner_state.dart';
import 'package:mobile_scanner/src/objects/scanner_error_widget.dart';
import 'package:mobile_scanner/src/scan_window_calculation.dart';
/// The function signature for the error builder.
typedef MobileScannerErrorBuilder = Widget Function(
BuildContext,
MobileScannerException,
Widget?,
);
/// This widget displays a live camera preview for the barcode scanner.
class MobileScanner extends StatefulWidget {
/// Create a new [MobileScanner] using the provided [controller].
const MobileScanner({
this.controller,
this.onDetect,
this.onDetectError = _onDetectErrorHandler,
this.fit = BoxFit.cover,
this.errorBuilder,
this.overlayBuilder,
this.placeholderBuilder,
this.scanWindow,
this.scanWindowUpdateThreshold = 0.0,
super.key,
});
/// The controller for the camera preview.
final MobileScannerController? controller;
/// The function that signals when new codes were detected by the [controller].
///
/// To handle both [BarcodeCapture]s and [MobileScannerBarcodeException]s,
/// use the [MobileScannerController.barcodes] stream directly (recommended),
/// or provide a function to [onDetectError].
final void Function(BarcodeCapture barcodes)? onDetect;
/// The error handler equivalent for the [onDetect] function.
///
/// If [onDetect] is not null, and this is null, errors are silently ignored.
final void Function(Object error, StackTrace stackTrace) onDetectError;
/// The error builder for the camera preview.
///
/// If this is null, a black [ColoredBox],
/// with a centered white [Icons.error] icon is used as error widget.
final MobileScannerErrorBuilder? errorBuilder;
/// The [BoxFit] for the camera preview.
///
/// Defaults to [BoxFit.cover].
final BoxFit fit;
/// The builder for the overlay above the camera preview.
///
/// The resulting widget can be combined with the [scanWindow] rectangle
/// to create a cutout for the camera preview.
///
/// The [BoxConstraints] for this builder
/// are the same constraints that are used to compute the effective [scanWindow].
///
/// The overlay is only displayed when the camera preview is visible.
final LayoutWidgetBuilder? overlayBuilder;
/// The placeholder builder for the camera preview.
///
/// If this is null, a black [ColoredBox] is used as placeholder.
///
/// The placeholder is displayed when the camera preview is being initialized.
final Widget Function(BuildContext, Widget?)? placeholderBuilder;
/// The scan window rectangle for the barcode scanner.
///
/// If this is not null, the barcode scanner will only scan barcodes
/// which intersect this rectangle.
///
/// This rectangle is relative to the layout size
/// of the *camera preview widget* in the widget tree,
/// rather than the actual size of the camera preview output.
/// This is because the size of the camera preview widget
/// might not be the same as the size of the camera output.
///
/// For example, the applied [fit] has an effect on the size of the camera preview widget,
/// while the camera preview size remains the same.
///
/// The following example shows a scan window that is centered,
/// fills half the height and one third of the width of the layout:
///
/// ```dart
/// LayoutBuider(
/// builder: (BuildContext context, BoxConstraints constraints) {
/// final Size layoutSize = constraints.biggest;
///
/// final double scanWindowWidth = layoutSize.width / 3;
/// final double scanWindowHeight = layoutSize.height / 2;
///
/// final Rect scanWindow = Rect.fromCenter(
/// center: layoutSize.center(Offset.zero),
/// width: scanWindowWidth,
/// height: scanWindowHeight,
/// );
/// }
/// );
/// ```
final Rect? scanWindow;
/// The threshold for updates to the [scanWindow].
///
/// If the [scanWindow] would be updated,
/// due to new layout constraints for the scanner,
/// and the width or height of the new scan window have not changed by this threshold,
/// then the scan window is not updated.
///
/// It is recommended to set this threshold
/// if scan window updates cause performance issues.
///
/// Defaults to no threshold for scan window updates.
final double scanWindowUpdateThreshold;
@override
State<MobileScanner> createState() => _MobileScannerState();
/// This empty function is used as the default error handler for [onDetect].
static void _onDetectErrorHandler(Object error, StackTrace stackTrace) {
// Do nothing.
}
}
class _MobileScannerState extends State<MobileScanner>
with WidgetsBindingObserver {
late final MobileScannerController controller;
/// The current scan window.
Rect? scanWindow;
/// Calculate the scan window based on the given [constraints].
///
/// If the [scanWindow] is already set, this method does nothing.
void _maybeUpdateScanWindow(
MobileScannerState scannerState,
BoxConstraints constraints,
) {
if (widget.scanWindow == null) {
return;
}
final Rect newScanWindow = calculateScanWindowRelativeToTextureInPercentage(
widget.fit,
widget.scanWindow!,
textureSize: scannerState.size,
widgetSize: constraints.biggest,
);
// The scan window was never set before.
// Set the initial scan window.
if (scanWindow == null) {
scanWindow = newScanWindow;
unawaited(controller.updateScanWindow(scanWindow));
return;
}
// The scan window did not not change.
// The left, right, top and bottom are the same.
if (scanWindow == newScanWindow) {
return;
}
// The update threshold is not set, allow updating the scan window.
if (widget.scanWindowUpdateThreshold == 0.0) {
scanWindow = newScanWindow;
unawaited(controller.updateScanWindow(scanWindow));
return;
}
final double dx = (newScanWindow.width - scanWindow!.width).abs();
final double dy = (newScanWindow.height - scanWindow!.height).abs();
// The new scan window has changed enough, allow updating the scan window.
if (dx >= widget.scanWindowUpdateThreshold ||
dy >= widget.scanWindowUpdateThreshold) {
scanWindow = newScanWindow;
unawaited(controller.updateScanWindow(scanWindow));
}
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<MobileScannerState>(
valueListenable: controller,
builder: (BuildContext context, MobileScannerState value, Widget? child) {
// If the controller is still initializing, show a black screen, or user provided placeholder
if (!value.isInitialized) {
const Widget defaultPlaceholder = ColoredBox(color: Colors.black);
return widget.placeholderBuilder?.call(context, child) ??
defaultPlaceholder;
}
final MobileScannerException? error = value.error;
// If the controller encountered, show an error screen, or user provided placeholder
if (error != null) {
final Widget defaultError = ScannerErrorWidget(error: error);
return widget.errorBuilder?.call(context, error, child) ??
defaultError;
}
return LayoutBuilder(
builder: (context, constraints) {
_maybeUpdateScanWindow(value, constraints);
final Widget? overlay =
widget.overlayBuilder?.call(context, constraints);
final Size cameraPreviewSize = value.size;
final Widget scannerWidget = ClipRect(
child: SizedBox.fromSize(
size: constraints.biggest,
child: FittedBox(
fit: widget.fit,
child: SizedBox(
width: cameraPreviewSize.width,
height: cameraPreviewSize.height,
child: MobileScannerPlatform.instance.buildCameraView(),
),
),
),
);
if (overlay == null) {
return scannerWidget;
}
return Stack(
alignment: Alignment.center,
children: <Widget>[
scannerWidget,
overlay,
],
);
},
);
},
);
}
StreamSubscription? _subscription;
Future<void> initController() async {
// TODO: This will be fixed in another PR
// If debug mode is enabled, stop the controller first before starting it.
// If a hot-restart is initiated, the controller won't be stopped, and because
// there is no way of knowing if a hot-restart has happened, we must assume
// every start is a hot-restart.
// if (kDebugMode) {
// try {
// await controller.stop();
// } catch (e) {
// // Don't do anything if the controller is already stopped.
// debugPrint('$e');
// }
// }
if (widget.onDetect != null) {
WidgetsBinding.instance.addObserver(this);
_subscription = controller.barcodes.listen(
widget.onDetect,
onError: widget.onDetectError,
cancelOnError: false,
);
}
if (controller.autoStart) {
await controller.start();
}
}
Future<void> disposeCamera() async {
if (controller.autoStart) {
await controller.stop();
}
// Dispose default controller if not provided by user
if (widget.controller == null) {
await controller.dispose();
WidgetsBinding.instance.removeObserver(this);
}
}
@override
void initState() {
super.initState();
controller = widget.controller ?? MobileScannerController();
unawaited(initController());
}
@override
void dispose() {
if (_subscription != null) {
_subscription!.cancel();
_subscription = null;
}
disposeCamera();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (widget.controller != null || !controller.value.hasCameraPermission) {
return;
}
switch (state) {
case AppLifecycleState.detached:
case AppLifecycleState.hidden:
case AppLifecycleState.paused:
return;
case AppLifecycleState.resumed:
_subscription = controller.barcodes.listen(
widget.onDetect,
onError: widget.onDetectError,
cancelOnError: false,
);
unawaited(controller.start());
case AppLifecycleState.inactive:
unawaited(_subscription?.cancel());
_subscription = null;
unawaited(controller.stop());
}
}
}