Skip to content

Commit

Permalink
emit barcode errors through the channel
Browse files Browse the repository at this point in the history
  • Loading branch information
navaronbracke committed Jun 18, 2024
1 parent 67f7e8f commit 4fead48
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
25 changes: 22 additions & 3 deletions lib/src/method_channel/mobile_scanner_method_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ import 'package:mobile_scanner/src/objects/start_options.dart';

/// An implementation of [MobileScannerPlatform] that uses method channels.
class MethodChannelMobileScanner extends MobileScannerPlatform {
/// The name of the error event that is sent when a barcode scan error occurs.
@visibleForTesting
static const String kBarcodeErrorEventName = 'MOBILE_SCANNER_BARCODE_ERROR';

/// The method channel used to interact with the native platform.
@visibleForTesting
final methodChannel = const MethodChannel(
Expand All @@ -40,11 +44,22 @@ class MethodChannelMobileScanner extends MobileScannerPlatform {
int? _textureId;

/// Parse a [BarcodeCapture] from the given [event].
///
/// If the event name is [kBarcodeErrorEventName],
/// a [MobileScannerBarcodeException] is thrown.
BarcodeCapture? _parseBarcode(Map<Object?, Object?>? event) {
if (event == null) {
return null;
}

if (event
case {
'name': kBarcodeErrorEventName,
'data': final String? errorDescription
}) {
throw MobileScannerBarcodeException(errorDescription);
}

final Object? data = event['data'];

if (data == null || data is! List<Object?>) {
Expand Down Expand Up @@ -133,9 +148,13 @@ class MethodChannelMobileScanner extends MobileScannerPlatform {

@override
Stream<BarcodeCapture?> get barcodesStream {
return eventsStream
.where((event) => event['name'] == 'barcode')
.map((event) => _parseBarcode(event));
// Handle both incoming barcode events and barcode error events.
return eventsStream.where(
(event) {
return event['name'] == 'barcode' ||
event['name'] == kBarcodeErrorEventName;
},
).map((event) => _parseBarcode(event));
}

@override
Expand Down
3 changes: 3 additions & 0 deletions lib/src/mobile_scanner_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ class MobileScannerController extends ValueNotifier<MobileScannerState> {
StreamController.broadcast();

/// Get the stream of scanned barcodes.
///
/// If an error occurred during the detection of a barcode,
/// an [MobileScannerBarcodeException] error is emitted to the stream.
Stream<BarcodeCapture> get barcodes => _barcodesController.stream;

StreamSubscription<BarcodeCapture?>? _barcodesSubscription;
Expand Down

0 comments on commit 4fead48

Please sign in to comment.