Skip to content

Commit e9b3ad4

Browse files
committed
handle barcode error events in the method channel implementation
1 parent 8bc967c commit e9b3ad4

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

lib/src/method_channel/mobile_scanner_method_channel.dart

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,22 +44,11 @@ class MethodChannelMobileScanner extends MobileScannerPlatform {
4444
int? _textureId;
4545

4646
/// Parse a [BarcodeCapture] from the given [event].
47-
///
48-
/// If the event name is [kBarcodeErrorEventName],
49-
/// a [MobileScannerBarcodeException] is thrown.
5047
BarcodeCapture? _parseBarcode(Map<Object?, Object?>? event) {
5148
if (event == null) {
5249
return null;
5350
}
5451

55-
if (event
56-
case {
57-
'name': kBarcodeErrorEventName,
58-
'data': final String? errorDescription
59-
}) {
60-
throw MobileScannerBarcodeException(errorDescription);
61-
}
62-
6352
final Object? data = event['data'];
6453

6554
if (data == null || data is! List<Object?>) {
@@ -94,6 +83,19 @@ class MethodChannelMobileScanner extends MobileScannerPlatform {
9483
);
9584
}
9685

86+
/// Parse a [MobileScannerBarcodeException] from the given [error] and [stackTrace], and throw it.
87+
///
88+
/// If the error is not a [PlatformException],
89+
/// with [kBarcodeErrorEventName] as [PlatformException.code], the error is rethrown as-is.
90+
Never _parseBarcodeError(Object error, StackTrace stackTrace) {
91+
if (error case PlatformException(:final String code, :final String? message)
92+
when code == kBarcodeErrorEventName) {
93+
throw MobileScannerBarcodeException(message);
94+
}
95+
96+
Error.throwWithStackTrace(error, stackTrace);
97+
}
98+
9799
/// Request permission to access the camera.
98100
///
99101
/// Throws a [MobileScannerException] if the permission is not granted.
@@ -136,13 +138,12 @@ class MethodChannelMobileScanner extends MobileScannerPlatform {
136138

137139
@override
138140
Stream<BarcodeCapture?> get barcodesStream {
139-
// Handle both incoming barcode events and barcode error events.
140-
return eventsStream.where(
141-
(event) {
142-
return event['name'] == 'barcode' ||
143-
event['name'] == kBarcodeErrorEventName;
144-
},
145-
).map((event) => _parseBarcode(event));
141+
// Handle incoming barcode events.
142+
// The error events are transformed to `MobileScannerBarcodeException` where possible.
143+
return eventsStream
144+
.where((e) => e['name'] == 'barcode')
145+
.map((event) => _parseBarcode(event))
146+
.handleError(_parseBarcodeError);
146147
}
147148

148149
@override

0 commit comments

Comments
 (0)