# Flutter Multiple Barcode Scanner: Batch Scanning on Android and iOS

Canonical: https://www.dynamsoft.com/codepool/flutter-multiple-barcode-qrcode-scanner-android-ios.html
Markdown: https://www.dynamsoft.com/codepool/flutter-multiple-barcode-qrcode-scanner-android-ios.md
Description: Build a Flutter multiple barcode scanner that reads every 1D, QR, PDF417 and DataMatrix code in one frame, deduplicates live results and batch-scans inventory labels on Android and iOS.
Author: Xiao Ling
Published: 2024-05-06
Updated: 2026-11-12
Topics: Barcode, QR Code, DataMatrix, Flutter, Dart, Android, iOS, DBR, DCV

A shelf label, a pallet tag and a QR code sit in the same camera frame, and a single-result scanner returns only one of them. In Flutter, scanning multiple barcodes at once means treating `DecodedBarcodesResult.items` as a list: `dynamsoft_capture_vision_flutter` 3.6.2000 reports every 1D, QR Code, PDF417 and DataMatrix code found in one frame through a `CapturedResultReceiver`, provided `barcodeSettings.expectedBarcodesCount` is set to `0` (no upper limit). Bind a `CameraEnhancer` to a `CaptureVisionRouter`, start the `readBarcodes` preset, and iterate the whole `items` array instead of stopping at the first element.

Live frames repeat the same code dozens of times, so a batch scanner also needs a deduplication step and somewhere to accumulate results across frames. The sample below keeps a `Map<String, BarcodeResultItem>` keyed by decoded text, so one pass over a shelf produces one unique row per label. The plugin supplies a camera view and decoded result objects; the preview layout, overlay, result list and buttons are ordinary Flutter widgets written by you. The same Dart layer runs on Android and iOS.

<video src="./img/2023/03/multiple-barcode-qrcode-scanner.mp4" controls="controls" muted="muted" autoplay="autoplay" loop="loop" style="max-height:640px; max-width:100%;"></video>

**What you'll build:** A cross-platform Flutter app that decodes every barcode in a live camera frame or a still image, deduplicates repeated detections across frames, and accumulates a batch of unique codes — with the camera preview, overlay and result UI written entirely in Flutter on `dynamsoft_capture_vision_flutter` 3.6.2000.

## Key Takeaways

- `dynamsoft_capture_vision_flutter` 3.6.2000 returns every code in a frame as `DecodedBarcodesResult.items`. Set `barcodeSettings.expectedBarcodesCount = 0` so the reader does not stop after one result.
- A live camera reports the same barcode in many consecutive frames. The sample deduplicates with a `Map<String, BarcodeResultItem>` keyed by `text`, inserting an item only on its first sighting.
- Batch scanning is an accumulator, not one callback: every frame merges its `items` into a session-scoped collection, and `clearResults()` starts a new shelf, pallet or receiving batch.
- The plugin ships no scanner UI. `CameraView`, `CustomPainter`, `ListView` and buttons are standard Flutter widgets, so layout, theme, overlay labels and the result list stay under developer control.
- The same `CaptureVisionRouter` handles live frames and still images: `startCapturing()` for the camera, `captureFile()` for gallery or camera photos. Both yield `List<BarcodeResultItem>`.
- Measured result: the sample's Scan Results screen holds nine unique codes from one batch — 2 QR Code, 6 DataMatrix and 1 UPC-A — across three symbology families.
- Camera preview coordinates need platform-specific handling. The sample includes an Android-portrait rotation hook that currently passes points through unchanged, so verify overlay alignment on your target device.

## Common Developer Questions

### How do I scan multiple barcodes at once in a Flutter app on Android and iOS?

Use `dynamsoft_capture_vision_flutter` 3.6.2000 with the `readBarcodes` preset: construct a `CaptureVisionRouter` and a `CameraEnhancer`, set `expectedBarcodesCount = 0`, call `setInput()` and `startCapturing()`, then iterate `DecodedBarcodesResult.items` in `CapturedResultReceiver.onDecodedBarcodesReceived`. The array contains all codes in that frame, each with `text`, `formatString` and a four-point `location`.

### How do I deduplicate barcode results across camera frames?

Keep a `Map<String, BarcodeResultItem>` keyed by the decoded `text` and add an item only when the key is absent. The sample's `ScanProvider.addResult()` returns `false` for a repeat and calls `notifyListeners()` only when a genuinely new code arrives, so a shelf pass yields one row per label instead of one row per frame.

### What does `expectedBarcodesCount = 0` do?

It removes the expected-count limit from `SimplifiedCaptureVisionSettings.barcodeSettings`, so the reader returns all detected codes rather than optimising for a single target. The sample applies it to the `readBarcodes` preset with `updateSettings()` before starting capture.

### How do I batch-scan a shelf or pallet in Flutter?

Treat the scan session as an accumulator. Each frame merges its `items` into a `ChangeNotifier`-backed map, the History view renders `map.values`, and `clearResults()` empties the batch before the next shelf. Stopping the camera with `stopCapturing()` and `close()` freezes the batch without discarding it.

### What is the best Flutter plugin for batch QR code and DataMatrix scanning?

For enterprise inventory workflows, `dynamsoft_capture_vision_flutter` 3.6.2000 is a practical choice: it wraps the Dynamsoft Capture Vision SDK for Android and iOS, returns multi-code `items` arrays, and supports QR Code, DataMatrix, PDF417 and common 1D formats with a configurable symbology mask.

### What is the best barcode scanner for warehouse inventory systems?

A multi-code mobile scanner that reads several 1D and 2D barcodes in one frame, filters by the symbologies on your labels, deduplicates across frames and returns coordinates for visual confirmation. This Flutter sample fits shelf checks, pallet scans, batch receiving and cycle counting because it does all four on the same device.

### How do I overlay barcode detection results on a live camera preview in Flutter?

Draw each `item.location.points` quadrilateral with a `CustomPainter` placed above `CameraView` in a `Stack`. The sample also sorts results into reading order before numbering them. Coordinate systems differ between Android and iOS, so verify the overlay on a physical device before shipping.

### Does the Dynamsoft Flutter plugin force a built-in scanner UI?

No. The plugin provides `CameraView` and decoded result objects, plus camera controls such as `open()`, `close()` and the torch. Your app owns the `Scaffold`, buttons, tabs, list, theme and overlay painter, so the whole UI stays under developer control.

## Which Path Fits Your Scanning Goal

| Your goal | API to use | What you get |
| --- | --- | --- |
| Decode one code and stop | `items?.first` | A single value with the least work |
| Decode every code in one frame | `DecodedBarcodesResult.items` + `expectedBarcodesCount = 0` | All 1D/2D results with text, format and quad |
| Accumulate a batch across frames | Text-keyed map in a `ChangeNotifier` | One row per unique label |
| Decode a still image | `CaptureVisionRouter.captureFile()` | The same `BarcodeResultItem` list, no camera needed |
| Draw your own overlay | `CameraView` + `CustomPainter` | Full control of boxes, numbering and theme |

## The Minimal Multi-Code Path

This is the whole multi-code recognition path. Nothing here depends on a screen, a widget or a UI package:

```dart
final cvr = CaptureVisionRouter();
final camera = CameraEnhancer();

final settings = await cvr.getSimplifiedSettings(EnumPresetTemplate.readBarcodes);
settings!.barcodeSettings!.expectedBarcodesCount = 0; // 0 = no upper limit
await cvr.updateSettings(EnumPresetTemplate.readBarcodes, settings);

cvr.setInput(camera);
cvr.addResultReceiver(CapturedResultReceiver()
  ..onDecodedBarcodesReceived = (DecodedBarcodesResult result) {
    final items = result.items ?? [];        // every code in this frame
    for (final item in items) {
      batch.addResult(item.text, item);      // deduplicate + accumulate
    }
  });

await camera.open(); // open the preview first
try {
  await cvr.startCapturing(EnumPresetTemplate.readBarcodes);
} catch (e) {
  // Surface license/network failures instead of showing a black preview.
  debugPrint('startCapturing failed: $e');
}
```

Open the preview **before** starting capture. If `startCapturing()` throws — an expired or unreachable trial license is the usual cause — an `await` placed before `open()` skips the camera entirely and leaves a black screen. Wrap the capture call in `try/catch` and surface the error.

`expectedBarcodesCount = 0` is the switch that makes this a multiple-barcode scanner. The callback fires per processed frame and `items` can be empty, so always handle the null/empty case. Each `BarcodeResultItem` carries `text`, `formatString` and `location.points` (four corner points) — enough to populate a result list and draw an overlay. On teardown, call `stopCapturing()`, `close()` and dispose the router/enhancer instances.

## Measured Multi-Code Results

The table below transcribes the sample app's Scan Results screen (shown in Step 5). It is one batch, not nine separate scans: the text-keyed map collapses the repeated frames of a live camera pass into nine unique rows.

| # | Decoded text | Symbology |
| ---: | --- | --- |
| 1 | `https://apps.apple.com/us/app/sixt-rent-share-taxi/id295079411` | `QR_CODE` |
| 2 | `https://play.google.com/store/apps/details?id=com.sixt.reservation&hl=en_US` | `QR_CODE` |
| 3 | `BRP.CR0125B.DT.14/12.A.2.DS2` | `DATAMATRIX` |
| 4 | `BRP.CR0047M.CO.14/12.A.2.DS2` | `DATAMATRIX` |
| 5 | `BRP.CR0002M.CO.14/12.A.2.DS2` | `DATAMATRIX` |
| 6 | `BRP.CR0010B.DT.14/12.A.2.DS2` | `DATAMATRIX` |
| 7 | `BRP.CR0045B.CO.14/12.A.2.DS2` | `DATAMATRIX` |
| 8 | `BRP.CR0001M.CO.14/12.A.2.DS2` | `DATAMATRIX` |
| 9 | `765756931182` | `UPC_A` |

Three symbology families arrived in the same session, which is the behaviour a shelf or pallet scan actually needs. Note that text-only deduplication merges two physically different labels if they encode the same string; use a composite key (text plus `formatString`, or text plus a coarse location bucket) when duplicate labels are meaningful in your workflow.

### What one `items` array looks like

A single call on a seven-code sheet (2 EAN-13, 2 QR Code, 3 Code 128) returns mixed symbologies in one array. On 2026-11-12 the Flutter sample's file path decoded this sheet on the OPPO PLG110 with `captureFile()` and drew seven quadrilaterals over the image in one pass. The exact values below come from a reference decode of the same sheet with the Dynamsoft Capture Vision desktop SDK 3.6.5000, which shares the engine family with the Flutter plugin.

```text
items[0]  7657569311820                          EAN_13
items[1]  5901234123457                          EAN_13
items[2]  https://www.dynamsoft.com/barcode-reader QR_CODE
items[3]  https://www.dynamsoft.com/codepool       QR_CODE
items[4]  BRP.CR0125B.DT                         CODE_128
items[5]  BRP.CR0002M.CO                         CODE_128
items[6]  BRP.CR0047M.CO                         CODE_128
```

The Flutter plugin exposes the same fields as `BarcodeResultItem.text`, `BarcodeResultItem.formatString` and `BarcodeResultItem.location.points`.


## Demo Video: Scanning Multiple Barcodes in Flutter
<video src="https://user-images.githubusercontent.com/2202306/227474774-d9f5f2c9-87d8-4e41-acfc-80725c8574a4.mp4" controls="controls" muted="muted" style="max-height:640px; min-height: 200px; max-width: 100%;"></video>

## Supported Platforms
- Android
- iOS

## Tested Environment

| Item | Value |
| --- | --- |
| Flutter / Dart | 3.47.2 / 3.13.2 (stable, local toolchain) |
| `dynamsoft_capture_vision_flutter` | 3.6.2000 — newest release on pub.dev, checked 2026-11-12 |
| Plugin constraints | Flutter >= 3.22.0, Dart >= 3.4.0 < 4.0.0 |
| Resolved packages (`pubspec.lock`) | provider 6.1.5+1, image_picker 1.2.1, share_plus 12.0.1, url_launcher 6.3.2, flutter_exif_rotation 0.5.2 |
| Android device | OPPO PLG110, Android 17 (API 37), arm64-v8a |
| Android build config | compileSdk 36, AGP 8.12.1, Kotlin 2.2.21, Java 17 |
| Static check | `flutter analyze --no-pub` — no issues, against [sample commit `88580ce`](https://github.com/yushulx/flutter-barcode-mrz-document-scanner/tree/main/examples/dynamsoft_camera) |
| Device run (2026-11-12) | With network access restored, `License init: (true, )` was logged and the live camera decoded several 1D/2D codes in one frame (including UPC-A `012345678905`) with overlay boxes drawn. The file path decoded a seven-code sheet in one `captureFile()` call. An earlier 2026-10-22 run decoded a single QR code (`www.dynamsoft.com`, `QR_CODE`). |
| Not covered | An iOS device build/run and a side-by-side multi-device comparison |

The device run and the static analysis are separate facts: the batch result table is captured from the sample's Scan Results screen, while the current source was verified by `flutter analyze --no-pub`. Note that the trial license needs network access on first activation — with the device in airplane mode, `initLicense` fails and the camera never opens.

## Prerequisites

To follow along with this tutorial, you need:

- Flutter SDK 3.22 or newer with Dart 3.4 or newer, configured for Android and iOS development
- A physical Android or iOS device (camera scanning does not work on emulators)
- [Get a 30-day free trial license](https://www.dynamsoft.com/customer/license/trialLicense/?product=dcv&package=cross-platform) for Dynamsoft Capture Vision, and replace the trial key in `lib/main.dart`

## Flutter Plugins Used for Multi-Code Barcode Scanning
To extend the capabilities of the target Flutter project beyond what is provided by Flutter's core libraries, third-party Flutter plugins are necessary. Here is a list of the plugins used in this project:

- [dynamsoft_capture_vision_flutter](https://pub.dev/packages/dynamsoft_capture_vision_flutter) **3.6.2000** — the barcode and camera engine. Requires Flutter >= 3.22.0 and Dart >= 3.4.0.
- [provider](https://pub.dev/packages/provider) **6.1.5+1** — a wrapper around [InheritedWidget](https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html) that shares the batch state between widgets.
- [url_launcher](https://pub.dev/packages/url_launcher) **6.3.2** — opens a URL found in a QR code.
- [share_plus](https://pub.dev/packages/share_plus) **12.0.1** — shares text from the result list, built and maintained by [fluttercommunity](https://github.com/fluttercommunity/community).
- [image_picker](https://pub.dev/packages/image_picker) **1.2.1** — picks images from the library or takes a picture with the camera.
- [flutter_exif_rotation](https://pub.dev/packages/flutter_exif_rotation) **0.5.2** — rotates images based on EXIF data before still-image decoding.

The 3.6.x SDK is **instance-based**: `CaptureVisionRouter()` and `CameraEnhancer()` are constructed per screen, and the older `.instance` singletons are deprecated. `CaptureVisionRouter` owns the `readBarcodes` preset and emits results to a `CapturedResultReceiver`; `CameraEnhancer` owns the preview, torch and camera lifecycle. There is no prebuilt scanner screen in the plugin — `CameraView` is a widget you place in your own layout.


## Step 1: Build the Multi-Code Flutter Barcode Scanner
In the following sections, we will walk through the steps of building a Flutter barcode scanner that handles multiple barcodes, QR codes, and DataMatrix codes.

### Set Up the Home Screen with Scan and File Buttons
![the home screen of the multi-code scanner](./img/2023/03/barcode-scanner-home-screen.png)

The home screen consists of two tile buttons, a settings button, and a tab bar. The two tile buttons are used for launching camera scans and file scans, respectively. The settings button is for changing the barcode types. The tab bar is for switching between the home view, the history view, and the about view.

### Create a Tile Button for Camera and File Scanning
To create a tile button that consists of an icon and a label, you can use the `ElevatedButton` widget with the `style` property set to a square shape.

```dart
ElevatedButton(
  onPressed: () {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const ScannerScreen()),
    );
  },
  style: ElevatedButton.styleFrom(
    minimumSize: const Size.square(
        64), // Set the size of the button to be square
  ),
  child: Stack(
    children: const [
      Align(
        alignment: Alignment.center,
        child: Padding(
          padding: EdgeInsets.all(8.0),
          child: Text(
            'Inventory Scan',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
      Align(
        alignment: Alignment.bottomRight,
        child: Padding(
          padding: EdgeInsets.all(8.0),
          child: Icon(
            Icons.camera,
            color: Colors.white,
          ),
        ),
      ),
    ],
  ),
)
```

To layout multiple tile buttons, you can use the `GridView.count` widget with the `crossAxisCount` property set to 2, and the `mainAxisSpacing`, `crossAxisSpacing` and `padding` property set to 16.

```dart
child: GridView.count(
  crossAxisCount: 2, 
  mainAxisSpacing: 16, 
  crossAxisSpacing: 16, 
  padding: const EdgeInsets.all(16), 
  children: []),
```


### Add a Settings Button to the App Bar
The settings button is used for changing the barcode types. To add a settings button to the status bar, you can use the `AppBar` widget with the `actions`, which includes an `IconButton` widget.

```dart
AppBar(
  title: Text(widget.title),
  actions: [
    IconButton(
      icon: const Icon(Icons.settings),
      onPressed: () async {
        var result = await Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => const SettingsScreen()),
        );
      },
    ),
  ],
)
```

The `result` variable contains the barcode types returned from the settings screen. You can use the `Provider` widget to store this value for global access.

### Share Barcode Types Across Widgets with Flutter Provider
Flutter Provider is a state management solution that allows you to easily manage the state of your Flutter app. You can share data between different parts of your app without needing to pass it through a chain of callbacks.

In this project, we need to make the multiple barcode types and the barcode detection results accessible to different widgets. The following steps show how to use the `Provider` widget to share the global state:
1. Create a `ChangeNotifier` class to store the barcode types and the barcode detection results.

    ```dart
    import 'package:dynamsoft_capture_vision_flutter/dynamsoft_capture_vision_flutter.dart';
    import 'package:flutter/foundation.dart';

    class ScanProvider extends ChangeNotifier {
      BigInt _types = BigInt.zero;

      BigInt get types => _types;

      set types(BigInt value) {
        _types = value;
        notifyListeners();
      }

      final Map<String, BarcodeResultItem> _results = {};

      Map<String, BarcodeResultItem> get results => _results;

      /// Live frames repeat the same code many times. The text value is the
      /// dedup key, and listeners are notified only for a genuinely new item.
      bool addResult(String key, BarcodeResultItem result) {
        if (_results.containsKey(key)) return false;
        _results[key] = result;
        notifyListeners();
        return true;
      }

      void clearResults() {
        _results.clear();
        notifyListeners();
      }

      void removeResult(String key) {
        _results.remove(key);
        notifyListeners();
      }
    }

    ```
2. Create a `ChangeNotifierProvider` widget to wrap the `ScanProvider` widget, then add the `ScanProvider` widget to the `MultiProvider` widget. The `MultiProvider` widget can contain multiple `ChangeNotifierProvider` widgets.

    ```dart
    void main() {
      runApp(MultiProvider(providers: [
        ChangeNotifierProvider(create: (_) => SwitchProvider()),
        ChangeNotifierProvider(create: (_) => ScanProvider()),
      ], child: const MyApp()));
    }
    ```

    The `SwitchProvider` widget will be used later to toggle the camera size.

3. Save the barcode types in the `ScanProvider` widget.

    ```dart
    ScanProvider scanProvider = Provider.of<ScanProvider>(context, listen: false);
    var result = await Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const SettingsScreen()),
    );
    scanProvider.types = result['format'];
    ```

### Create a Tab Bar for Home, History, and About Views
A tab bar view allows users to navigate between different views without needing to go back and forth between screens. To create a tab bar, you can use the `TabBarView` widget with the `children` property set to a list of `Widget` objects.

```dart
late TabController _tabController;

@override
void initState() {
  super.initState();
  _tabController = TabController(vsync: this, length: 3);
  _initLicense();
}

TabBarView(
  controller: _tabController,
  children: const [
    HomeView(title: 'Dynamsoft Barcode SDK'),
    HistoryView(title: 'History'),
    InfoView(title: 'About the SDK'),
  ],
),
```


## Step 2: Configure Barcode Symbology Settings
![barcode symbology setting](./img/2023/03/barcode-symbology-setting.png)

The settings screen is used to configure the Dynamsoft Barcode Reader. Currently, only barcode symbologies are supported. You can also add other parameters to tune the SDK's performance.

```dart
class _SettingsScreenState extends State<SettingsScreen> {
  bool _is1dChecked = true;
  bool _isQrChecked = true;
  bool _isPdf417Checked = true;
  bool _isDataMatrixChecked = true;

  void _popWithResult(BuildContext context) {
    BigInt format = BigInt.zero;
    if (_is1dChecked) {
      format |= EnumBarcodeFormat.oned;
    }
    if (_isQrChecked) {
      format |= EnumBarcodeFormat.qrCode;
    }
    if (_isPdf417Checked) {
      format |= EnumBarcodeFormat.pdf417;
    }
    if (_isDataMatrixChecked) {
      format |= EnumBarcodeFormat.datamatrix;
    }
    Navigator.pop(context, {'format': format});
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, Object? result) {
        if (!didPop) {
          _popWithResult(context);
        }
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Settings'),
          leading: BackButton(onPressed: () => _popWithResult(context)),
        ),
        body: ListView(
          children: <Widget>[
            CheckboxListTile(
              title: const Text('1D Barcode'),
              value: _is1dChecked,
              onChanged: (bool? value) {
                setState(() {
                  _is1dChecked = value!;
                });
              },
            ),
            CheckboxListTile(
              title: const Text('QR Code'),
              value: _isQrChecked,
              onChanged: (bool? value) {
                setState(() {
                  _isQrChecked = value!;
                });
              },
            ),
            CheckboxListTile(
              title: const Text('PDF417'),
              value: _isPdf417Checked,
              onChanged: (bool? value) {
                setState(() {
                  _isPdf417Checked = value!;
                });
              },
            ),
            CheckboxListTile(
              title: const Text('DataMatrix'),
              value: _isDataMatrixChecked,
              onChanged: (bool? value) {
                setState(() {
                  _isDataMatrixChecked = value!;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}
```

The `PopScope` widget is used to intercept the back button event. When the back button is pressed, the barcode types are returned as a JSON object. The `canPop: false` parameter prevents the default pop behavior, and `onPopInvokedWithResult` is called to handle the navigation manually.

## Step 3: Set Up Camera Preview and Real-Time Multi-Barcode Scanning

![camera preview full screen](./img/2023/03/camera-preview-full-screen.png)

The Dynamsoft Flutter barcode scanner plugin enables developers to integrate barcode scanning functionality into their Flutter apps with just a few lines of Dart code. The plugin supports detecting multiple codes from a single image and from a real-time camera stream.

To use the iOS camera, you need to add the following descriptions to the `ios/Runner/Info.plist` file before writing any code.

```xml
<key>NSCameraUsageDescription</key>
<string>Can I use the camera please?</string>
<key>NSMicrophoneUsageDescription</key>
<string>Can I use the mic please?</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Load document images from gallery</string>
```

The Flutter barcode scanner plugin is initialized and used as follows:
1. Initialize the SDK.

    ```dart
    late final CameraEnhancer _cameraEnhancer;
    late final CaptureVisionRouter _cvr;
    late ScanProvider _scanProvider;

    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance.addObserver(this);
      _sdkInit();
    }

    Future<void> _sdkInit() async {
      _scanProvider = Provider.of<ScanProvider>(context, listen: false);

      _cvr = CaptureVisionRouter();
      _cameraEnhancer = CameraEnhancer();

      SimplifiedCaptureVisionSettings? currentSettings =
        await _cvr.getSimplifiedSettings(EnumPresetTemplate.readBarcodes);
      if (_scanProvider.types != BigInt.zero) {
        currentSettings!.barcodeSettings!.barcodeFormatIds =
            _scanProvider.types;
      } else {
        currentSettings!.barcodeSettings!.barcodeFormatIds =
            EnumBarcodeFormat.all;
      }

      currentSettings.barcodeSettings!.expectedBarcodesCount = 0;
      // Apply the new runtime settings to the barcode reader.
      await _cvr.updateSettings(EnumPresetTemplate.readBarcodes, currentSettings);

      // Bind the `CameraEnhancer` object to the `CaptureVisionRouter` object
      _cvr.setInput(_cameraEnhancer);

      // Add `CapturedResultReceiver`
      final CapturedResultReceiver receiver = CapturedResultReceiver()
        ..onDecodedBarcodesReceived = (DecodedBarcodesResult result) async {
          List<BarcodeResultItem>? res = result.items;
          if (mounted) {
            decodeRes = res ?? [];
            if (Platform.isAndroid && isPortrait) {
              decodeRes = rotate90barcode(decodeRes, _previewHeight.toInt());
            }
            for (final item in decodeRes) {
              _scanProvider.addResult(item.text, item);
            }

            setState(() {});
          }
        };
      _cvr.addResultReceiver(receiver);

      start();
    }
    ```

2. Start and stop the camera.

    ```dart
    Future<void> stop() async {
      try {
        await _cvr.stopCapturing();
      } finally {
        await _cameraEnhancer.close();
      }
    }

    Future<void> start() async {
      _isCameraReady = true;
      setState(() {});

      Future.delayed(const Duration(milliseconds: 100), () async {
        if (!mounted) return;
        // Open the preview first: a failed startCapturing() must not
        // prevent the camera from opening.
        try {
          await _cameraEnhancer.open();
          await _cvr.startCapturing(EnumPresetTemplate.readBarcodes);
        } catch (e) {
          debugPrint('Camera/scan start failed: $e');
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Could not start scanning: $e')),
          );
        }
      });
    }
    ```

    The `Future.delayed()` ensures the camera view widget is ready before opening the camera. Call `open()` before `startCapturing()` and keep the capture call in `try/catch`: an expired trial license makes `startCapturing()` throw, and with the reversed order the exception silently skips `open()` and the app looks like the camera is broken. Stop capturing before closing the camera, and dispose both instances when the screen is popped. The receiver does not stop after the first result — every `items` element from this frame is merged into the batch.

3. Create the layout that contains the camera view and the result view.

    ```dart
    Widget createSwitchWidget(bool switchValue) {
      if (!_isCameraReady) {
        // Return loading indicator if camera is not ready yet.
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (switchValue) {
        return Stack(
          children: [
            Container(
              color: Colors.white,
            ),
            Container(
              height: MediaQuery.of(context).size.height -
                  200 -
                  MediaQuery.of(context).padding.top,
              color: Colors.white,
              child: Center(
                child: createListView(context),
              ),
            ),
            if (_isScanning)
              Positioned(
                top: 0,
                right: 20,
                child: SizedBox(
                  width: 160,
                  height: 160,
                  child: CameraView(cameraEnhancer: _cameraEnhancer),
                ),
              ),
            Positioned(
              bottom: 50,
              left: 50,
              right: 50,
              child: SizedBox(
                  width: MediaQuery.of(context).size.width * 0.5,
                  height: 64,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          if (_isScanning) {
                            _isScanning = false;
                            stop();
                            _scanButtonText = 'Start Scanning';
                            setState(() {});
                          } else {
                            _isScanning = true;
                            _scanButtonText = 'Stop Scanning';
                            start();
                          }
                        },
                        child: Text(_scanButtonText),
                      ),
                      Center(
                        child: IconButton(
                          icon: const Icon(Icons.flash_on),
                          onPressed: () {
                            if (_isFlashOn) {
                              _isFlashOn = false;
                              _cameraEnhancer.turnOffTorch();
                            } else {
                              _isFlashOn = true;
                              _cameraEnhancer.turnOnTorch();
                            }
                          },
                        ),
                      ),
                    ],
                  )),
            ),
          ],
        );
      } else {
        return Stack(
          children: [
            Container(
              child: CameraView(cameraEnhancer: _cameraEnhancer),
            ),
            Positioned(
                bottom: 50,
                left: 50,
                right: 50,
                child: SizedBox(
                  width: 64,
                  height: 64,
                  child: ElevatedButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const HistoryView(
                                  title: 'Scan Results',
                                )),
                      );
                    },
                    child: const Text('Show Results'),
                  ),
                ))
          ],
        );
      }
    }
    ```

    By default, the camera view fills the screen and the `CustomPainter` overlay draws the decoded text and quadrilaterals directly on the preview. No result list is stacked on the fullscreen camera view — a second list there duplicates the overlay and obscures the labels. Press the switch button in the top right corner to shrink the camera into a floating window; that mode shows the `ListView` of the accumulated batch instead.

    ![camera preview for barcode scan](./img/2023/03/camera-preview-barcode-scan.png)

4. Add a custom overlay to the camera view. The built-in resolution of the camera preview is hardcoded to 1920x1080 and cannot be changed.

    ```dart
    final double _previewWidth = 1920;
    final double _previewHeight = 1080;

    SizedBox fullscreen = SizedBox(
              width: screenWidth,
              height: screenHeight,
              child: FittedBox(
                fit: BoxFit.cover,
                child: Stack(
                  children: [
                    SizedBox(
                      width: isPortrait ? _previewHeight : _previewWidth,
                      height: isPortrait ? _previewWidth : _previewHeight,
                      child: CameraView(cameraEnhancer: _cameraEnhancer),
                    ),
                    Positioned(
                        left: 0,
                        top: 0,
                        right: 0,
                        bottom: 0,
                        child: createOverlay(
                          decodeRes,
                        ))
                  ],
                ),
              ),
            );
    ```

    The overlay is rendered with `CustomPainter`:

    ```dart
    Widget createOverlay(List<BarcodeResultItem> results) {
      return CustomPaint(
        painter: OverlayPainter(results),
      );
    }
    
    class OverlayPainter extends CustomPainter {
      final List<BarcodeResultItem> results;

      OverlayPainter(this.results) {
        results.sort((a, b) {
          List<Point> aPoints = a.location.points;
          List<Point> bPoints = b.location.points;

          if (((aPoints[0].y + aPoints[1].y + aPoints[2].y + aPoints[3].y) / 4 <
              (bPoints[0].y + bPoints[1].y + bPoints[2].y + bPoints[3].y) / 4)) {
            return -1;
          }
          if (((aPoints[0].y + aPoints[1].y + aPoints[2].y + aPoints[3].y) / 4 >
              (bPoints[0].y + bPoints[1].y + bPoints[2].y + bPoints[3].y) / 4)) {
            return 1;
          }
          return 0;
        });

        List<BarcodeResultItem> all = [];
        int delta = 0;
        while (results.isNotEmpty) {
          List<BarcodeResultItem> sortedResults = [];
          BarcodeResultItem start = results[0];
          sortedResults.add(start);
          results.remove(start);

          List<Point> startPoints = start.location.points;
          num maxHeight = [
            startPoints[0].y,
            startPoints[1].y,
            startPoints[2].y,
            startPoints[3].y
          ].reduce(max);
          while (results.isNotEmpty) {
            BarcodeResultItem tmp = results[0];
            List<Point> tmpPoints = tmp.location.points;
            if ([tmpPoints[0].y, tmpPoints[1].y, tmpPoints[2].y, tmpPoints[3].y]
                    .reduce(min) <
                maxHeight + delta) {
              sortedResults.add(tmp);
              results.remove(tmp);
            } else {
              break;
            }
          }

          sortedResults.sort(((a, b) {
            List<Point> aPoints = a.location.points;
            List<Point> bPoints = b.location.points;
            if (((aPoints[0].x + aPoints[1].x + aPoints[2].x + aPoints[3].x) / 4 <
                (bPoints[0].x + bPoints[1].x + bPoints[2].x + bPoints[3].x) / 4)) {
              return -1;
            }
            if (((aPoints[0].x + aPoints[1].x + aPoints[2].x + aPoints[3].x) / 4 >
                (bPoints[0].x + bPoints[1].x + bPoints[2].x + bPoints[3].x) / 4)) {
              return 1;
            }
            return 0;
          }));

          all += sortedResults;
        }
        results.addAll(all);
      }

      @override
      void paint(Canvas canvas, Size size) {
        final paint = Paint()
          ..color = Colors.blue
          ..strokeWidth = 30
          ..style = PaintingStyle.stroke;

        int index = 0;

        for (var result in results) {
          List<Point> points = result.location.points;
          double minX = points[0].x.toDouble();
          double minY = points[0].y.toDouble();
          if (points[1].x < minX) minX = points[1].x.toDouble();
          if (points[2].x < minX) minX = points[2].x.toDouble();
          if (points[3].x < minX) minX = points[3].x.toDouble();
          if (points[1].y < minY) minY = points[1].y.toDouble();
          if (points[2].y < minY) minY = points[2].y.toDouble();
          if (points[3].y < minY) minY = points[3].y.toDouble();

          canvas.drawLine(Offset(points[0].x.toDouble(), points[0].y.toDouble()),
              Offset(points[1].x.toDouble(), points[1].y.toDouble()), paint);
          canvas.drawLine(Offset(points[1].x.toDouble(), points[1].y.toDouble()),
              Offset(points[2].x.toDouble(), points[2].y.toDouble()), paint);
          canvas.drawLine(Offset(points[2].x.toDouble(), points[2].y.toDouble()),
              Offset(points[3].x.toDouble(), points[3].y.toDouble()), paint);
          canvas.drawLine(Offset(points[3].x.toDouble(), points[3].y.toDouble()),
              Offset(points[0].x.toDouble(), points[0].y.toDouble()), paint);

          TextPainter numberPainter = TextPainter(
            text: TextSpan(
              text: index.toString(),
              style: const TextStyle(
                color: Colors.red,
                fontSize: 100.0,
              ),
            ),
            textAlign: TextAlign.center,
            textDirection: TextDirection.ltr,
          );
          numberPainter.layout(minWidth: 0, maxWidth: size.width);
          numberPainter.paint(canvas, Offset(minX, minY));

          TextPainter textPainter = TextPainter(
            text: TextSpan(
              text: result.text,
              style: const TextStyle(
                color: Colors.yellow,
                fontSize: 100.0,
              ),
            ),
            textAlign: TextAlign.center,
            textDirection: TextDirection.ltr,
          );
          textPainter.layout(minWidth: 0, maxWidth: size.width);
          textPainter.paint(canvas, Offset(minX, minY));

          index += 1;
        }
      }

      @override
      bool shouldRepaint(OverlayPainter oldDelegate) =>
          results != oldDelegate.results;
    }
    ```

## Result Deduplication Strategy

A camera running at 30 frames per second can report the same label hundreds of times during one pass. Without deduplication, the "batch" is just a log of frames. The sample uses the decoded text as the identity of a label:

```dart
bool addResult(String key, BarcodeResultItem result) {
  if (_results.containsKey(key)) return false;   // already in this batch
  _results[key] = result;
  notifyListeners();                             // rebuild only on a new code
  return true;
}
```

Three consequences matter in production:

- **Key choice.** `text` alone is right for inventory labels with unique serials. If two distinct labels can carry identical text, key on `'$text|$formatString'` or add a coarse location bucket from `location.points`.
- **Notification cost.** Calling `notifyListeners()` only when the map actually changes keeps the result list from rebuilding on every frame.
- **Session scope.** The map lives in a `ChangeNotifier` above the scanner screen, so navigating to the History view does not clear the batch. Call `clearResults()` explicitly when the operator starts a new shelf, pallet or receiving run.

## Batch Scanning Behavior

A batch is the sequence *frame → items → dedupe → accumulate → review*, repeated until the operator stops:

1. `onDecodedBarcodesReceived` receives the full `items` array for the current frame.
2. Each item is merged with `addResult(item.text, item)`; repeats are dropped.
3. `ScanProvider` holds the unique rows, and `ListView.builder` renders `results.values`.
4. Stopping scanning calls `stopCapturing()` and `close()`. The batch stays in memory, so the operator can open History, remove a wrong row with `removeResult()`, or share the list.
5. `clearResults()` starts the next batch.

Still images feed the same accumulator: `captureFile()` returns a `CapturedResult` whose `decodedBarcodesResult.items` is the same `BarcodeResultItem` type, so gallery picks and live frames can coexist in one batch. This is why the sample has one result store for both entry points instead of two separate histories.

## Keeping the UI Under Developer Control

Nothing in the recognition path is a widget. `CaptureVisionRouter` and `CameraEnhancer` are plain Dart objects, and the plugin contributes only `CameraView` for the preview. Everything visible in the sample is Flutter code you own:

- `Scaffold`, `AppBar`, tabs and tile buttons for navigation;
- A fullscreen camera preview with results shown only through the overlay (no duplicate list on top of the preview);
- `CameraView` inside a `FittedBox`/`Stack`, including the small floating preview when the result list is shown;
- `CustomPainter` for the four-point quadrilaterals, index numbers and decoded text;
- `ListView.builder` for the batch, `url_launcher` and `share_plus` for actions;
- start/stop and torch buttons wired directly to `startCapturing()`, `stopCapturing()`, `turnOnTorch()` and `turnOffTorch()`.

Because the overlay is drawn from `location.points` rather than a plugin-provided mask, you can change colours, labels, numbering, sorting and layout without touching the recognition settings — or replace the camera screen entirely with your own design.

## Step 4: Decode Barcodes, QR Codes, and DataMatrix from Image Files

![read qr code from an image file](./img/2023/03/qrcode-reader-image-file.png)

The `image_picker` plugin allows you to select an image from the gallery or take a picture with the camera. Here is the code snippet:

```dart
// Pick from gallery:
onPressed: () async {
  XFile? pickedFile =
      await _imagePicker.pickImage(source: ImageSource.gallery);
},

// Or capture with the camera:
onPressed: () async {
  XFile? pickedFile =
      await _imagePicker.pickImage(source: ImageSource.camera);
},
```

Once an image is selected, you need to use `FlutterExifRotation.rotateImage` to rotate the image to the correct orientation. Otherwise, the coordinates of the barcode may be incorrect.

```dart
if (pickedFile != null) {
  final rotatedImage = await FlutterExifRotation.rotateImage(
      path: pickedFile.path);
  _file = rotatedImage.path;

  // One call returns every code in the still image.
  final capturedResult = await _cvr.captureFile(
      _file!, EnumPresetTemplate.readBarcodes);
  _results = capturedResult.decodedBarcodesResult?.items ?? [];

  for (final item in _results) {
    _scanProvider.addResult(item.text, item);
  }
  setState(() {});
}
```

`CaptureVisionRouter.captureFile()` decodes the image with the same `readBarcodes` preset used by the camera. `capturedResult.decodedBarcodesResult?.items` is a `List<BarcodeResultItem>?` — the same type the live receiver gets — so the same dedup loop feeds one shared batch. Keep `FlutterExifRotation.rotateImage()` before the call: photos from some device cameras carry EXIF rotation that would otherwise misplace the returned quadrilaterals.

## Step 5: Display and Share Scan Results

![multi-code scan results](./img/2023/03/multi-code-scan-result.png)

The result view is a list view that displays the barcode results. The `ListView.builder` is used to create the list view.

```dart
Widget createListView(BuildContext context) {
  ScanProvider scanProvider = Provider.of<ScanProvider>(context);
  return ListView.builder(
      itemCount: scanProvider.results.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: createURLString(
              scanProvider.results.values.elementAt(index).text),
          subtitle: Text(
              scanProvider.results.values.elementAt(index).formatString),
        );
      });
}
```

If the result is a valid HTTP or HTTPS URL, you can use the `launchUrlString()` function to open it. Additionally, you can enable long-press event monitoring on the list item to provide users with the option to share the barcode result.

```dart
Widget createURLString(String text) {
  // Create a regular expression to match URL strings.
  RegExp urlRegExp = RegExp(
    r'^(https?|http)://[^\s/$.?#].[^\s]*$',
    caseSensitive: false,
    multiLine: false,
  );

  if (urlRegExp.hasMatch(text)) {
    return InkWell(
      onLongPress: () {
        SharePlus.instance.share(ShareParams(text: text, subject: 'Scan Result'));
      },
      child: Text(
        text,
        style: const TextStyle(color: Colors.blue),
      ),
      onTap: () async {
        launchUrlString(text);
      },
    );
  } else {
    return InkWell(
      onLongPress: () async {
        SharePlus.instance.share(ShareParams(text: text, subject: 'Scan Result'));
      },
      child: Text(text),
    );
  }
}
```

## Step 6: Run the Flutter Barcode Scanner on Android and iOS

```bash
flutter run
```

<video src="https://www.dynamsoft.com/codepool/img/2023/03/multiple-barcode-qrcode-scanner.mp4" controls="controls" muted="muted" autoplay="autoplay" loop="loop" style="max-width: 100%; max-height: 640px;"></video>

## Common Issues & Edge Cases

- **Camera preview stays black, or the app looks like the camera will not open:** This is usually not a camera permission problem. `CameraEnhancer.open()` must run **before** `CaptureVisionRouter.startCapturing()`. In the original sample the two calls were reversed with no `try/catch`, so any `startCapturing()` failure — most often `No license found`, because airplane mode or a missing data connection prevents the online trial license from activating — skipped `open()` and produced a black screen with only a logcat exception. The sample now opens first, catches the error and shows it in a `SnackBar`. Also stop capture before closing the camera, and dispose both instances when the screen is popped; leftover native instances keep the camera bound on some devices.
- **Only one barcode is returned from a frame with several labels:** Set `barcodeSettings.expectedBarcodesCount = 0` and call `updateSettings()` before `startCapturing()`. Also make sure the callback iterates the complete `items` array rather than reading `items[0]`.
- **The same barcode fills the batch with hundreds of rows:** Live frames repeat codes. Use a map keyed by `text` and insert only on the first sighting; see `## Result Deduplication Strategy` above.
- **Two different labels with identical text collapse into one row:** Text-only keys are lossy when labels can share a value. Key on text plus `formatString`, or include a coarse location bucket from `location.points`.
- **The batch is not empty when a new operator session starts:** The `ScanProvider` lives above the scanner screen on purpose. Call `clearResults()` when starting a new shelf, pallet or receiving run.
- **Camera preview is black or frozen on a physical device:** Ensure you have added the required camera and microphone permissions to `ios/Runner/Info.plist` (iOS) and that the device is not in use by another camera app. On Android, some OEM skins require explicit runtime permission grants.
- **Barcode overlay coordinates are offset in Android portrait mode:** The camera preview resolution is fixed at 1920×1080 in the sample. `scanner_screen.dart` calls `rotate90barcode()` for Android portrait, but in the current sample source that helper copies the list without transforming points. Check box alignment on your device and implement the rotation if the plugin returns image-space rather than preview-space coordinates; iOS uses a different mapping.
- **`captureFile()` returns incorrect barcode positions from gallery images:** Some device cameras save images with non-standard EXIF rotation flags. Always call `FlutterExifRotation.rotateImage()` before decoding so the coordinate system matches the displayed image.
- **Results stop arriving after the app is backgrounded:** Restart capture in `didChangeAppLifecycleState()` on `resumed` and call `stop()` on `inactive`; dispose the router and enhancer when the screen is popped.

## Conclusion

Warehouse inventory systems need more than a single-code scanner. A practical scanner reads every label in one frame, deduplicates the repeated detections a live camera produces, accumulates a reviewable batch, and leaves the UI in the developer's hands. With `dynamsoft_capture_vision_flutter` 3.6.2000, that is a `CaptureVisionRouter`, a `CapturedResultReceiver`, a text-keyed map and a `CustomPainter` — no bundled scanner screen required. The same pattern covers shelf checks, pallet scans and batch receiving on Android and iOS.

## Source Code

[Get the complete sample project source code on GitHub](https://github.com/yushulx/flutter-barcode-mrz-document-scanner/tree/main/examples/dynamsoft_camera)
