Skip to content

Use cases ​

How apps use flutter_zxing, each case one file to copy into your app. It imports only flutter_zxing and Flutter, plus the package it names. The same files run in the demo's Use cases tab: open a case there to try it on your phone.

Scanning ​

A scan button ​

One code, then back to your screen.

Try it in the demo

scan_button.dart
dart
// A scan button: the app needs one code, opens the scanner, gets the code
// and goes on. scanBarcode returns null when the user closes the scanner.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class ScanButtonPage extends StatefulWidget {
  const ScanButtonPage({super.key});

  @override
  State<ScanButtonPage> createState() => _ScanButtonPageState();
}

class _ScanButtonPageState extends State<ScanButtonPage> {
  Barcode? _barcode;

  Future<void> _scan() async {
    final Barcode? barcode = await scanBarcode(
      context,
      formats: {BarcodeFormat.qrCode}, // fewer formats read faster
      hint: 'Point the camera at a QR code',
    );
    if (barcode == null || !mounted) return; // closed
    setState(() => _barcode = barcode);
  }

  @override
  Widget build(BuildContext context) {
    final Barcode? barcode = _barcode;
    return Scaffold(
      appBar: AppBar(title: const Text('A scan button')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (barcode != null) ...[
                Text(barcode.format.displayName),
                const SizedBox(height: 8),
                SelectableText(
                  barcode.text,
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 24),
              ],
              FilledButton.icon(
                onPressed: _scan,
                icon: const Icon(Icons.qr_code_scanner),
                label: Text(barcode == null ? 'Scan a QR code' : 'Scan again'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Your brand’s look ​

Your colors, buttons, scan window, texts and widgets.

Try it in the demo

custom_look.dart
dart
// Your brand's look: the scanner in your colors, shapes and icons, with a
// scan window sized and placed for your codes, your own texts and a widget
// of your own over the camera. Three looks to switch between: a bank, a
// grocery till and a club door. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

/// A text of the scanner in your words: subclass the built-in translation
/// of your app's language and override what you need.
class _TillTexts extends ScannerLocalizationsEn {
  @override
  String get scanAgain => 'Next item';
}

/// One look: a template with its window, a theme and texts.
typedef _Look = ({
  String name,
  ScannerTemplate template,
  ScannerTheme theme,
  ScannerLocalizations? texts,
});

final List<_Look> _looks = [
  (
    name: 'Bank',
    // A card-shaped window for payment QR codes, buttons and panels in the
    // bank's pale blue, a plain white sheet, square corners, bolder texts
    // and the app's Material icons on the buttons.
    template: const ScannerTemplate.minimal(
      title: 'Pay by QR code',
      hint: 'Fit the payment code in the frame',
      scanWindow: ScanWindow.centered(width: 0.85, aspectRatio: 1.6),
      formats: {BarcodeFormat.qrCode},
      zoomButtons: false,
    ),
    theme: const ScannerTheme(
      accent: Color(0xFF1D4ED8),
      brightness: Brightness.light,
      buttonShape: ScannerButtonShape.roundedSquare,
      windowRadius: 6,
      glass: Color(0xFFEAF0FF), // opaque: no blur behind it
      sheet: Color(0xFFFFFFFF),
      sheetRadius: 16,
      textStyles: ScannerTextStyles(
        title: TextStyle(fontWeight: FontWeight.w700),
        hint: TextStyle(fontWeight: FontWeight.w600),
      ),
      icons: ScannerIconSet(
        close: ScannerIconData.fromIconData(Icons.arrow_back),
        torchOn: ScannerIconData.fromIconData(Icons.flashlight_on_outlined),
        torchOff: ScannerIconData.fromIconData(Icons.flashlight_off_outlined),
        photo: ScannerIconData.fromIconData(Icons.photo_library_outlined),
        switchCamera: ScannerIconData.fromIconData(Icons.cameraswitch_outlined),
      ),
    ),
    texts: null, // the app's language
  ),
  (
    name: 'Grocery',
    // A wide, low window for product barcodes with a till's red laser and
    // still brackets without dimming, the torch for dark shelves, and "Next
    // item" instead of "Scan again".
    template: ScannerTemplate.minimal(
      hint: 'Barcode on the product',
      scanWindow: const ScanWindow.centered(
        width: 0.9,
        aspectRatio: 3,
        alignment: Alignment(0, 0.2),
      ),
      formats: BarcodeFormat.retail,
      photoButton: false,
    ),
    theme: const ScannerTheme(
      accent: Color(0xFFFF6A1A),
      brightness: Brightness.dark,
      windowRadius: 4,
      windowShape: ScannerWindowShape.bracketsOnly,
      breathing: false,
      scanLine: ScanLine(color: Color(0xFFFF1A1A)), // costs some energy
    ),
    texts: _TillTexts(),
  ),
  (
    name: 'Club',
    // A small round window high up, pink on dark glass with pink arcs over
    // a deep violet scrim, and its own colors for a ticket that was used or
    // is not valid.
    template: const ScannerTemplate.minimal(
      title: 'Door',
      hint: 'Ticket QR code',
      scanWindow: ScanWindow.centered(
        width: 0.55,
        alignment: Alignment(0, -0.35),
      ),
      formats: {BarcodeFormat.qrCode},
    ),
    theme: const ScannerTheme(
      accent: Color(0xFFFF3FA4),
      brightness: Brightness.dark,
      windowShape: ScannerWindowShape.circle,
      window: Color(0xFFFF8CC6),
      scrim: Color(0xC21A0B2E),
      bracketWidth: 4,
      bracketLength: 28,
      warning: Color(0xFFFFD60A),
      danger: Color(0xFFFF453A),
      // fontFamily: 'YourBrandFont', // a font your app bundles
    ),
    texts: null,
  ),
];

class CustomLookPage extends StatefulWidget {
  const CustomLookPage({super.key});

  @override
  State<CustomLookPage> createState() => _CustomLookPageState();
}

class _CustomLookPageState extends State<CustomLookPage> {
  _Look _look = _looks.first;

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text('Your brand’s look'),
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(56),
        child: Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: SegmentedButton<_Look>(
            segments: [
              for (final look in _looks)
                ButtonSegment(value: look, label: Text(look.name)),
            ],
            selected: {_look},
            onSelectionChanged: (s) => setState(() => _look = s.first),
          ),
        ),
      ),
    ),
    body: BarcodeScanner(
      template: _look.template,
      theme: _look.theme,
      texts: _look.texts,
      // Your own widget over the camera, in the look's glass.
      // Under the template's top bar, clear of the result sheet below.
      foregroundBuilder: (context, layout) => Positioned(
        left: 0,
        right: 0,
        top: MediaQuery.paddingOf(context).top + 72,
        child: Center(
          child: ScannerGlass(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
            child: Text(
              '${_look.name} · a widget of yours',
              style: ScannerTheme.of(context).labelStyle,
            ),
          ),
        ),
      ),
    ),
  );
}

Buttons of your own ​

Your buttons under the scan window, the built-in ones moved.

Try it in the demo

own_buttons.dart
dart
// Buttons of your own under the scan window, placed with foregroundBuilder,
// while the built-in zoom and camera switch move with controlsLayout.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class OwnButtonsPage extends StatefulWidget {
  const OwnButtonsPage({super.key});

  @override
  State<OwnButtonsPage> createState() => _OwnButtonsPageState();
}

class _OwnButtonsPageState extends State<OwnButtonsPage> {
  ScannerControlsLayout _controls = ScannerControlsLayout.adaptive;

  void _help() => ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Hold the code flat, about a hand away')),
  );

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text('Buttons of your own'),
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(56),
        child: Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: SegmentedButton<ScannerControlsLayout>(
            segments: const [
              ButtonSegment(
                value: ScannerControlsLayout.adaptive,
                label: Text('Bottom'),
              ),
              ButtonSegment(
                value: ScannerControlsLayout.sideColumn,
                label: Text('Side'),
              ),
              ButtonSegment(
                value: ScannerControlsLayout.topBar,
                label: Text('Top'),
              ),
            ],
            selected: {_controls},
            onSelectionChanged: (s) => setState(() => _controls = s.first),
          ),
        ),
      ),
    ),
    body: BarcodeScanner(
      // The built-in torch and photo buttons off: yours replace them. The
      // zoom and the camera switch stay, where controlsLayout puts them
      // (a side column needs room beside the window, as on a tablet).
      template: ScannerTemplate.minimal(
        torchButton: false,
        photoButton: false,
        controlsLayout: _controls,
      ),
      foregroundBuilder: (context, layout) {
        // Hidden while a result shows: the scanner pauses then.
        if (layout.state.status != ScannerStatus.running) {
          return const SizedBox.shrink();
        }
        final Rect window = layout.scanWindow;
        final buttons = <Widget>[
          TorchButton(layout.controller),
          PickImageButton(layout.controller),
          ScannerButton(
            icon: const ScannerIconData.fromIconData(Icons.help_outline),
            label: 'Help',
            onPressed: _help,
          ),
        ];
        // Under the window and its hint; at its left in landscape, where
        // there is no room below it.
        if (layout.size.width > layout.size.height) {
          return Positioned(
            right: layout.size.width - window.left + 24,
            top: window.top,
            bottom: layout.size.height - window.bottom,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              spacing: 16,
              children: buttons,
            ),
          );
        }
        return Positioned(
          left: 0,
          right: 0,
          top: window.bottom + 72,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 24,
            children: buttons,
          ),
        );
      },
    ),
  );
}

Scan into a form ​

A serial number, IMEI or tracking number into a text field.

Try it in the demo

scan_into_form.dart
dart
// Scan into a form: a scan button in each text field fills it from the
// barcode on the box, for a form that asks for a serial number, an IMEI or
// a tracking number. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class ScanIntoFormPage extends StatefulWidget {
  const ScanIntoFormPage({super.key});

  @override
  State<ScanIntoFormPage> createState() => _ScanIntoFormPageState();
}

class _ScanIntoFormPageState extends State<ScanIntoFormPage> {
  final TextEditingController _serial = TextEditingController();
  final TextEditingController _imei = TextEditingController();
  final TextEditingController _tracking = TextEditingController();

  @override
  void dispose() {
    _serial.dispose();
    _imei.dispose();
    _tracking.dispose();
    super.dispose();
  }

  // An IMEI is 15 digits; the box also carries other Code 128 barcodes,
  // such as the EAN or the serial number, which the scanner refuses here.
  static ScanVerdict? _checkImei(Barcode barcode) =>
      RegExp(r'^\d{15}$').hasMatch(barcode.text)
      ? null
      : const ScanVerdict.reject(
          title: 'Not an IMEI',
          message: 'Scan the barcode next to "IMEI" on the box.',
        );

  void _register() {
    // Your code: send the device to your server.
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text('Registered ${_serial.text}')));
  }

  Widget _field(String label, TextEditingController controller, Widget scan) =>
      Padding(
        padding: const EdgeInsets.only(bottom: 16),
        child: TextField(
          controller: controller,
          decoration: InputDecoration(
            labelText: label,
            border: const OutlineInputBorder(),
            suffixIcon: scan,
          ),
        ),
      );

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Register a device')),
    body: ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _field(
          'Serial number',
          _serial,
          ScanFieldButton(
            controller: _serial,
            title: 'Serial number',
            formats: {BarcodeFormat.code128, BarcodeFormat.dataMatrix},
          ),
        ),
        _field(
          'IMEI',
          _imei,
          ScanFieldButton(
            controller: _imei,
            title: 'IMEI',
            formats: {BarcodeFormat.code128},
            check: _checkImei,
          ),
        ),
        _field(
          'Tracking number',
          _tracking,
          ScanFieldButton(
            controller: _tracking,
            title: 'Tracking number',
            formats: BarcodeFormat.linear, // the label's barcode
          ),
        ),
        const SizedBox(height: 8),
        FilledButton(onPressed: _register, child: const Text('Register')),
      ],
    ),
  );
}

Sign in on another screen ​

Your TV or web app shows a QR code, the phone confirms.

Try it in the demo

sign_in_with_qr.dart
dart
// Sign in on another screen: your TV or web app shows a QR code, the
// signed-in phone scans it and confirms. To try it, scan a QR code of
// https://example.com/login/TV-4821. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class SignInWithQrPage extends StatefulWidget {
  const SignInWithQrPage({super.key});

  @override
  State<SignInWithQrPage> createState() => _SignInWithQrPageState();
}

class _SignInWithQrPageState extends State<SignInWithQrPage> {
  // Your code: the address your other screen puts in its QR code.
  static const String _prefix = 'https://example.com/login/';

  String? _session; // the screen signed in, once confirmed

  // Only your service's login codes; anything else keeps the scanner open.
  static ScanVerdict? _check(Barcode barcode) =>
      barcode.text.startsWith(_prefix) && barcode.text.length > _prefix.length
      ? null
      : const ScanVerdict.reject(
          title: 'Not a sign-in code',
          message: 'Scan the code on the screen you want to sign in on.',
        );

  Future<void> _scan() async {
    final Barcode? barcode = await scanBarcode(
      context,
      template: const ScannerTemplate.signIn(check: _check),
    );
    if (barcode == null || !mounted) return; // closed
    final String session = barcode.text.substring(_prefix.length);
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Sign in on this screen?'),
        content: const Text('Only confirm if you started the sign-in there.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Cancel'),
          ),
          FilledButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Sign in'),
          ),
        ],
      ),
    );
    if (confirmed != true || !mounted) return;
    // Your code: send the session to your server with this user's token;
    // the other screen then signs in.
    setState(() => _session = session);
  }

  @override
  Widget build(BuildContext context) {
    final String? session = _session;
    return Scaffold(
      appBar: AppBar(title: const Text('Sign in on another screen')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                session == null ? Icons.tv_rounded : Icons.check_circle_rounded,
                size: 64,
              ),
              const SizedBox(height: 16),
              Text(
                session == null
                    ? 'Open the app on your TV or go to example.com, then scan '
                          'the code it shows.'
                    : 'Signed in on $session',
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.titleMedium,
              ),
              const SizedBox(height: 24),
              FilledButton.icon(
                onPressed: _scan,
                icon: const Icon(Icons.qr_code_scanner),
                label: Text(session == null ? 'Scan the code' : 'Another one'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Show where a QR code leads before opening it.

Try it in the demo

open_link.dart
dart
// Open a link safely: the sheet shows where a QR code leads before the
// browser opens it, and warns about a link without https. Android, iOS,
// macOS, the web. Also needs url_launcher.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:url_launcher/url_launcher.dart';

class OpenLinkPage extends StatelessWidget {
  const OpenLinkPage({super.key});

  // A link without https gets a warning on the sheet, under its domain.
  static ScanVerdict? _check(Barcode barcode) => switch (barcode.content) {
    UrlContent(:final url) when url.scheme == 'http' => const ScanVerdict.warn(
      title: 'Not secure',
      message:
          'What you send there can be read on the way: '
          'no passwords or card numbers.',
    ),
    _ => null,
  };

  static List<ScannerAction> _actions(
    BuildContext context,
    ScannerResult result,
  ) => [
    if (result.barcode.content case UrlContent(:final url))
      ScannerAction(
        label: result.verdict?.kind == ScanVerdictKind.warn
            ? 'Open anyway'
            : 'Open',
        icon: ScannerIcons.open,
        primary: true,
        onPressed: () => launchUrl(url, mode: LaunchMode.externalApplication),
      ),
    ...result.defaultActions,
  ];

  @override
  Widget build(BuildContext context) => const Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.content(
        check: _check,
        actionsBuilder: _actions,
      ),
    ),
  );
}

Wi‑Fi from a QR code ​

The network and its password, copied in a tap.

Try it in the demo

join_wifi.dart
dart
// Wi‑Fi from a QR code: the network's name, its security and the password
// with a Copy button, for the code on a café table or a router. Joining the
// network from the app needs a platform plugin. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class JoinWifiPage extends StatelessWidget {
  const JoinWifiPage({super.key});

  // Other QR codes keep the scanner open.
  static final ScannerCheck _check = acceptOnly<WifiContent>(
    reject: const ScanVerdict.reject(title: 'Not a Wi‑Fi code'),
  );

  static Widget? _sheet(BuildContext context, ScannerResult result) {
    final BarcodeContent content = result.barcode.content;
    // Anything else, such as a code from a photo: the default sheet.
    if (content is! WifiContent) return null;
    final ScannerTheme theme = ScannerTheme.of(context);
    final ScannerLocalizations texts = ScannerLocalizations.of(context);
    final String? password = content.password;
    return ScannerSheet(
      label: 'Wi‑Fi network',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('WI‑FI', style: theme.overlineStyle),
          const SizedBox(height: 4),
          Text(content.ssid, style: theme.titleStyle),
          Text(texts.wifiSecurityOf(content.security), style: theme.mutedStyle),
          if (content.hidden) Text('Hidden network', style: theme.mutedStyle),
          if (password != null && password.isNotEmpty) ...[
            const SizedBox(height: 16),
            Text('Password', style: theme.labelStyle),
            SelectableText(password, style: theme.dataStyle),
          ],
          const SizedBox(height: 16),
          // Your code: join the network with a Wi‑Fi plugin; without one,
          // the user pastes the password in the system's Wi‑Fi settings.
          ScannerActions([
            if (password != null && password.isNotEmpty)
              ScannerAction.copy(
                password,
                label: 'Copy password',
                primary: true,
              ),
            ScannerAction.scanAgain(result.scanAgain),
          ]),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.content(
        hint: 'Scan the Wi‑Fi code',
        check: _check,
        resultBuilder: _sheet,
      ),
    ),
  );
}

Pay by QR code ​

SEPA, Swiss QR-bill, UPI, PIX... into your payment screen.

Try it in the demo

pay_by_qr.dart
dart
// Pay by QR code: a payment code (SEPA GiroCode, Swiss QR-bill, UPI, PIX
// and other EMVCo codes, SPAYD, ГОСТ) into your app's confirm screen, with
// the payee, account, amount and reference filled in. To try it, scan the
// payment QR code of an invoice. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class PayByQrPage extends StatelessWidget {
  const PayByQrPage({super.key});

  // A code with a wrong IBAN or checksum is not a payment, so it is refused
  // here too.
  static final ScannerCheck _check = acceptOnly<PaymentContent>(
    reject: const ScanVerdict.reject(title: 'Not a payment code'),
  );

  // The default sheet shows the payee and the amount; Pay goes on.
  static List<ScannerAction> _actions(
    BuildContext context,
    ScannerResult result,
  ) => [
    if (result.barcode.content case final PaymentContent payment)
      ScannerAction(
        label: 'Pay',
        primary: true,
        onPressed: () async {
          final bool? paid = await Navigator.of(context).push<bool>(
            MaterialPageRoute(builder: (_) => _ConfirmPage(payment)),
          );
          if (paid ?? false) result.scanAgain();
        },
      ),
    ...result.defaultActions,
  ];

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.payment(
        check: _check,
        actionsBuilder: _actions,
      ),
    ),
  );
}

/// Your app's confirm screen, filled from the code.
class _ConfirmPage extends StatefulWidget {
  const _ConfirmPage(this.payment);

  final PaymentContent payment;

  @override
  State<_ConfirmPage> createState() => _ConfirmPageState();
}

class _ConfirmPageState extends State<_ConfirmPage> {
  // The amount is text such as '12.50'; null when the payer enters it.
  late final TextEditingController _amount = TextEditingController(
    text: widget.payment.amount,
  );

  @override
  void dispose() {
    _amount.dispose();
    super.dispose();
  }

  void _pay() {
    // Your code: hand the payment to your bank or payment provider.
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Paid ${_amount.text} to ${widget.payment.payee}'),
      ),
    );
    Navigator.pop(context, true);
  }

  @override
  Widget build(BuildContext context) {
    final PaymentContent payment = widget.payment;
    return Scaffold(
      appBar: AppBar(title: const Text('Confirm payment')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          ListTile(
            title: const Text('To'),
            subtitle: Text(payment.payee ?? ''),
          ),
          ListTile(
            title: const Text('Account'),
            subtitle: Text(payment.account ?? ''),
          ),
          if (payment.reference case final String reference)
            ListTile(title: const Text('Reference'), subtitle: Text(reference)),
          const SizedBox(height: 8),
          TextField(
            controller: _amount,
            readOnly: payment.amount != null, // the code sets the amount
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            decoration: InputDecoration(
              labelText: 'Amount',
              suffixText: payment.currency,
              border: const OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 24),
          FilledButton(onPressed: _pay, child: const Text('Confirm and pay')),
        ],
      ),
    );
  }
}

Look up a product ​

EAN, UPC or ISBN into your catalogue.

Try it in the demo

product_lookup.dart
dart
// Look up a product: the EAN, UPC or ISBN barcode of a product or a book
// in your catalogue, found or not. The check asks your server and keeps
// what it found for the sheet. To try it, scan 5901234123457 or the ISBN
// 9780306406157 (or any EAN). Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

typedef _Product = ({String name, String price});

class ProductLookupPage extends StatelessWidget {
  const ProductLookupPage({super.key});

  // Your code: ask your server. Products are listed by GTIN-14 (14 digits,
  // zeros in front), as product databases list them.
  static Future<_Product?> _find(String gtin) async {
    await Future<void>.delayed(const Duration(milliseconds: 300));
    return const <String, _Product>{
      '05901234123457': (name: 'Sparkling water 0.5 l', price: '€0.89'),
      '04006381333931': (name: 'Highlighter, yellow', price: '€1.49'),
      '09780306406157': (name: 'Introduction to Physics', price: '€24.90'),
    }[gtin];
  }

  // Runs before the sheet: it may wait for the server. The sheet shows the
  // verdict's title and message; its data goes to the buttons.
  static Future<ScanVerdict?> _check(Barcode barcode) async {
    final BarcodeContent content = barcode.content;
    if (content is! ProductContent) return null;
    final _Product? product = await _find(content.gtin);
    if (product == null) {
      return const ScanVerdict.warn(title: 'Not in the catalogue');
    }
    return ScanVerdict.accept(
      title: product.name,
      message: product.price,
      data: product,
    );
  }

  static List<ScannerAction> _actions(
    BuildContext context,
    ScannerResult result,
  ) => [
    if (result.verdict?.data case final _Product product)
      ScannerAction(
        label: 'Add to cart',
        primary: true,
        onPressed: () {
          // Your code: add the product to the cart.
          debugPrint('Added ${product.name}');
          result.scanAgain();
        },
      ),
    ...result.defaultActions,
  ];

  @override
  Widget build(BuildContext context) => const Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.product(
        check: _check,
        actionsBuilder: _actions,
      ),
    ),
  );
}

Boarding pass ​

Passenger, flight and seat from the pass.

Try it in the demo

boarding_pass.dart
dart
// Boarding pass: the passenger and each flight (from, to, flight, date,
// seat) from the PDF417 or Aztec code of a paper or mobile boarding pass,
// for a travel or lounge app. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class BoardingPassPage extends StatelessWidget {
  const BoardingPassPage({super.key});

  // Tickets and other codes keep the scanner open.
  static final ScannerCheck _check = acceptOnly<BoardingPassContent>(
    reject: const ScanVerdict.reject(title: 'Not a boarding pass'),
  );

  static Widget? _sheet(BuildContext context, ScannerResult result) {
    final BarcodeContent content = result.barcode.content;
    // Anything else, such as a code from a photo: the default sheet.
    if (content is! BoardingPassContent) return null;
    final ScannerTheme theme = ScannerTheme.of(context);
    final ScannerLocalizations texts = ScannerLocalizations.of(context);
    return ScannerSheet(
      label: 'Boarding pass',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // As printed: SURNAME/GIVEN NAMES.
          Text(content.passengerName, style: theme.overlineStyle),
          // One block per flight: a pass with a connection has two.
          for (final BoardingPassLeg leg in content.legs) ...[
            const SizedBox(height: 12),
            Text('${leg.from} → ${leg.to}', style: theme.titleStyle),
            const SizedBox(height: 8),
            ScannerFields({
              'Flight': '${leg.carrier} ${leg.flightNumber}',
              // The pass gives the day of the year, not the year.
              if (leg.date() case final DateTime day)
                'Date': texts.dayAndMonth(day),
              'Seat': leg.seat.isEmpty ? '–' : leg.seat,
              'Class': leg.cabin,
              'Booking': leg.bookingReference,
            }),
          ],
          const SizedBox(height: 16),
          ScannerActions([
            ScannerAction(
              label: 'Add to my trips',
              primary: true,
              onPressed: () {
                // Your code: save the pass to the user's trips.
                result.finish();
              },
            ),
            ScannerAction.scanAgain(result.scanAgain),
          ]),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.ticket(
        title: 'Scan your boarding pass',
        check: _check,
        resultBuilder: _sheet,
      ),
    ),
  );
}

Tickets at the door ​

Each ticket checked against the guest list, nonstop.

Try it in the demo

door_check_in.dart
dart
// Tickets at the door: the scanner never stops, each ticket is checked
// against the guest list and gets a green, amber or red verdict, and a
// counter shows how many came in, with your own sound for each verdict.
// Android, iOS, macOS, the web.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class DoorCheckInPage extends StatefulWidget {
  const DoorCheckInPage({super.key});

  @override
  State<DoorCheckInPage> createState() => _DoorCheckInPageState();
}

class _DoorCheckInPageState extends State<DoorCheckInPage> {
  // Your code: the guest list from your server, by ticket number.
  final Map<String, String> _guests = {
    'TICKET-1001': 'Anna Petrova',
    'TICKET-1002': 'Lucas Martin',
    'TICKET-1003': 'Mei Tanaka',
  };
  final Set<String> _inside = {};

  Future<ScanVerdict?> _check(Barcode barcode) async {
    final String ticket = barcode.text;
    final String? guest = _guests[ticket];
    if (guest == null) {
      return const ScanVerdict.reject(
        title: 'Not on the list',
        message: 'Send the guest to the box office.',
      );
    }
    if (!_inside.add(ticket)) {
      return ScanVerdict.warn(title: guest, message: 'Already checked in');
    }
    return ScanVerdict.accept(title: guest, message: 'Welcome!');
  }

  // Instead of the template's sounds and haptics.
  void _feedback(ScanFeedback kind) {
    // Your own sound: play your app's beep and buzz here, such as with an
    // audio package. This one only buzzes, harder for a refused ticket.
    unawaited(switch (kind) {
      ScanFeedback.rejected => HapticFeedback.vibrate(),
      ScanFeedback.warned => HapticFeedback.heavyImpact(),
      _ => HapticFeedback.lightImpact(),
    });
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.checkIn(
        check: _check,
        hint: 'Scan the ticket',
        onFeedback: _feedback,
      ),
    ),
  );
}

Stocktake ​

Many barcodes in a row, with counts.

Try it in the demo

stocktake.dart
dart
// Stocktake: scan the products on a shelf one after another, each barcode
// goes into a list with its count, and "Done" hands the list to the app to
// send. Try it with any product barcodes. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class StocktakePage extends StatefulWidget {
  const StocktakePage({super.key});

  @override
  State<StocktakePage> createState() => _StocktakePageState();
}

class _StocktakePageState extends State<StocktakePage> {
  /// The counted products once "Done" is tapped; `null` while scanning.
  List<CollectedBarcode>? _counted;
  bool _sending = false;

  Future<void> _send(List<CollectedBarcode> counted) async {
    setState(() => _sending = true);
    // Your code: send the count to your inventory system.
    final Map<String, int> count = {
      for (final item in counted) item.barcode.text: item.count,
    };
    await Future<void>.delayed(const Duration(seconds: 1));
    if (!mounted) return;
    setState(() => _sending = false);
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text('Sent ${count.length} products')));
  }

  @override
  Widget build(BuildContext context) {
    final List<CollectedBarcode>? counted = _counted;
    if (counted == null) {
      return Scaffold(
        body: BarcodeScanner(
          template: ScannerTemplate.retail(
            title: 'Aisle 4',
            sound: true, // a click for each scan, eyes stay on the shelf
            onDone: (items) => setState(() => _counted = items),
          ),
        ),
      );
    }
    final int total = counted.fold(0, (sum, item) => sum + item.count);
    return Scaffold(
      appBar: AppBar(title: Text('Aisle 4: $total items')),
      body: ListView(
        children: [
          for (final item in counted)
            ListTile(
              title: Text(item.barcode.text),
              subtitle: Text(item.barcode.format.displayName),
              trailing: Text(
                '× ${item.count}',
                style: Theme.of(context).textTheme.titleMedium,
              ),
            ),
        ],
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () => setState(() => _counted = null),
                  child: const Text('Count again'),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: FilledButton(
                  onPressed: _sending || counted.isEmpty
                      ? null
                      : () => _send(counted),
                  child: Text(_sending ? 'Sending…' : 'Send'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Receive parcels ​

GS1-128 shipping labels: SSCC, GTIN, quantity, batch.

Try it in the demo

parcels.dart
dart
// Receive parcels: scan the GS1-128 labels of incoming parcels and pallets;
// the SSCC, GTIN, quantity and batch of each go into a received list.
// Try it with a GS1-128 of (00)106141411234567897(02)09501101530003(37)12(10)LOT42.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class ParcelsPage extends StatefulWidget {
  const ParcelsPage({super.key});

  @override
  State<ParcelsPage> createState() => _ParcelsPageState();
}

class _ParcelsPageState extends State<ParcelsPage> {
  /// The labels once "Done" is tapped; `null` while scanning.
  List<Gs1Content>? _received;

  // Only GS1 labels go into the list.
  final ScannerCheck _check = acceptOnly<Gs1Content>(
    reject: const ScanVerdict.reject(
      title: 'Not a GS1 label',
      message: 'Scan the barcode with (00) under it',
    ),
  );

  void _done(List<CollectedBarcode> items) {
    // The check let only GS1 labels in.
    final List<Gs1Content> labels = [
      for (final item in items) item.barcode.content as Gs1Content,
    ];
    // Your code: book the parcels into your warehouse system.
    setState(() => _received = labels);
  }

  @override
  Widget build(BuildContext context) {
    final List<Gs1Content>? received = _received;
    if (received == null) {
      return Scaffold(
        body: BarcodeScanner(
          template: ScannerTemplate.logistics(
            title: 'Goods in: dock 2',
            check: _check,
            onDone: _done,
          ),
        ),
      );
    }
    return Scaffold(
      appBar: AppBar(title: Text('${received.length} parcels received')),
      body: ListView(
        children: [
          for (final label in received)
            ListTile(
              leading: const Icon(Icons.inventory_2_outlined),
              title: Text('SSCC ${label.sscc ?? '–'}'),
              subtitle: Text(
                [
                  // A pallet names its goods with AI 02, a trade item with 01.
                  if (label.gtin ?? label.contentsGtin case final gtin?)
                    'GTIN $gtin',
                  if (label.batch case final batch?) 'Batch $batch',
                ].join(' · '),
              ),
              trailing: label.count == null ? null : Text('× ${label.count}'),
            ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => setState(() => _received = null),
        icon: const Icon(Icons.qr_code_scanner),
        label: const Text('Scan more'),
      ),
    );
  }
}

Loyalty card at the till ​

The card number from its barcode, large.

Try it in the demo

loyalty_card.dart
dart
// A loyalty card at the till: scan the customer's card, look the number up
// and attach the customer and their points to the sale. Any card's barcode
// works: a card you do not know is enrolled. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class LoyaltyCardPage extends StatefulWidget {
  const LoyaltyCardPage({super.key});

  @override
  State<LoyaltyCardPage> createState() => _LoyaltyCardPageState();
}

typedef _Customer = ({String name, int points});

class _LoyaltyCardPageState extends State<LoyaltyCardPage> {
  // Your code: look the card number up in your loyalty system.
  final Map<String, _Customer> _members = {
    '4006123456789012': (name: 'Anna Petrova', points: 1240),
    '4006987654321098': (name: 'Lucas Martin', points: 85),
  };
  _Customer? _customer;

  Future<void> _scan() async {
    // The scanner's own screen with its sheet; "Attach" closes it with the
    // customer the check found.
    final _Customer? customer = await openScanner<_Customer>(
      context,
      template: ScannerTemplate.loyalty(
        title: 'Loyalty card',
        // The sheet shows the card number large, and under it the customer.
        check: (barcode) {
          final _Customer? member = _members[barcode.text];
          return member == null
              ? const ScanVerdict.warn(
                  title: 'Unknown card',
                  message: 'It will be enrolled',
                  data: (name: 'New member', points: 0),
                )
              : ScanVerdict.accept(
                  title: member.name,
                  message: '${member.points} points',
                  data: member,
                );
        },
        actionsBuilder: (context, result) => [
          ScannerAction(
            label: 'Attach to the sale',
            primary: true,
            onPressed: () => result.finish(result.verdict?.data),
          ),
          ScannerAction.scanAgain(result.scanAgain),
        ],
      ),
    );
    if (customer == null || !mounted) return; // closed
    setState(() => _customer = customer);
  }

  @override
  Widget build(BuildContext context) {
    final _Customer? customer = _customer;
    final TextTheme text = Theme.of(context).textTheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Till 1')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (customer != null) ...[
              Text(customer.name, style: text.headlineSmall),
              const SizedBox(height: 8),
              Text('${customer.points} points', style: text.titleMedium),
              const SizedBox(height: 24),
            ],
            FilledButton.icon(
              onPressed: _scan,
              icon: const Icon(Icons.card_membership),
              label: Text(
                customer == null ? 'Scan loyalty card' : 'Scan another',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Medicine pack ​

Batch, serial and expiry from the Data Matrix.

Try it in the demo

medicine_pack.dart
dart
// A medicine pack before it is dispensed: the GS1 Data Matrix gives the
// GTIN, batch, serial number and expiry date; expired packs and recalled
// batches are refused. Try it with a GS1 Data Matrix of
// (01)09506000134352(17)271231(10)A1B2C3(21)12345678901.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class MedicinePackPage extends StatelessWidget {
  const MedicinePackPage({super.key});

  // Your code: the batches your verification system has recalled.
  static const Set<String> _recalled = {'RECALL1'};

  ScanVerdict? _check(Barcode barcode, ScannerLocalizations texts) {
    final BarcodeContent content = barcode.content;
    if (content is! Gs1Content || content.gtin == null) {
      return const ScanVerdict.reject(
        title: 'Not a medicine pack',
        message: 'Scan the square code on the pack',
      );
    }
    if (content.isExpired()) {
      return ScanVerdict.reject(
        title: 'Expired',
        message:
            'Expired on ${texts.fullDate(content.expiryDate!)}. '
            'Do not dispense.',
      );
    }
    if (_recalled.contains(content.batch)) {
      return ScanVerdict.reject(
        title: 'Recalled batch',
        message: 'Batch ${content.batch}. Do not dispense.',
      );
    }
    return null; // accepted: the sheet shows the pack
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.pharma(
        title: 'Dispense',
        // The dates in the language of the scanner's texts.
        check: (barcode) => _check(barcode, ScannerLocalizations.of(context)),
        actionsBuilder: (context, result) => [
          ScannerAction(
            label: 'Dispense',
            primary: true,
            onPressed: () {
              // Your code: decommission the serial number in your national
              // verification system (FMD, DSCSA), then record the sale.
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('Pack dispensed')));
              result.scanAgain();
            },
          ),
          ...result.defaultActions,
        ],
      ),
    ),
  );
}

Vehicle VIN ​

The maker and model year from the windshield code.

Try it in the demo

vin.dart
dart
// A vehicle's VIN into a record: scan the code on the windshield or the
// door pillar and the form fills with the VIN, maker code, region and
// model year. Try it with a Code 39 of 1HGCM82633A004352.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class VinPage extends StatefulWidget {
  const VinPage({super.key});

  @override
  State<VinPage> createState() => _VinPageState();
}

class _VinPageState extends State<VinPage> {
  final TextEditingController _vin = TextEditingController();
  final TextEditingController _maker = TextEditingController();
  final TextEditingController _region = TextEditingController();
  final TextEditingController _year = TextEditingController();
  bool? _checkDigitOk;

  Future<void> _scan() async {
    final VinContent? vin = await scanContent<VinContent>(
      context,
      template: const ScannerTemplate.vin(),
      reject: const ScanVerdict.reject(title: 'Not a VIN'),
    );
    if (vin != null && mounted) {
      setState(() {
        _vin.text = vin.vin;
        _maker.text = vin.wmi; // Your code: the maker's name for the WMI
        // In the language of the scanner's texts (ScannerLocalizations).
        _region.text = ScannerLocalizations.of(context).vinRegionOf(vin.region);
        _year.text = vin.modelYear?.toString() ?? '';
        _checkDigitOk = vin.hasValidCheckDigit;
      });
    }
  }

  @override
  void dispose() {
    for (final c in [_vin, _maker, _region, _year]) {
      c.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('New vehicle')),
    body: ListView(
      padding: const EdgeInsets.all(16),
      children: [
        TextField(
          controller: _vin,
          decoration: InputDecoration(
            labelText: 'VIN',
            // Only North American VINs must carry the check digit.
            helperText: _checkDigitOk == false
                ? 'The check digit does not match: compare with the plate'
                : null,
            suffixIcon: IconButton(
              onPressed: _scan,
              icon: const Icon(Icons.qr_code_scanner),
              tooltip: 'Scan the VIN',
            ),
          ),
        ),
        TextField(
          controller: _maker,
          decoration: const InputDecoration(labelText: 'Maker code (WMI)'),
        ),
        TextField(
          controller: _region,
          decoration: const InputDecoration(labelText: 'Made in'),
        ),
        TextField(
          controller: _year,
          decoration: const InputDecoration(labelText: 'Model year'),
        ),
        const SizedBox(height: 24),
        FilledButton(
          // Your code: save the vehicle record.
          onPressed: () => Navigator.of(context).maybePop(),
          child: const Text('Save'),
        ),
      ],
    ),
  );
}

Self-service kiosk ​

The front camera, large text, no buttons.

Try it in the demo

kiosk.dart
dart
// A self-service kiosk for order pickup: the customer holds the QR code
// from their order e-mail up to the front camera, and a large verdict says
// which locker opens. Try it with a QR code of ORDER-1001; a long press in
// the top-left corner leaves.
// Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class KioskPage extends StatefulWidget {
  const KioskPage({super.key});

  @override
  State<KioskPage> createState() => _KioskPageState();
}

class _KioskPageState extends State<KioskPage> {
  // Your code: the orders ready for pickup, from your server.
  final Map<String, ({String name, int locker})> _ready = {
    'ORDER-1001': (name: 'Anna', locker: 4),
    'ORDER-1002': (name: 'Lucas', locker: 7),
    'ORDER-1003': (name: 'Mei', locker: 12),
  };
  final Set<String> _collected = {};

  Future<ScanVerdict?> _check(Barcode barcode) async {
    final String order = barcode.text;
    final ready = _ready[order];
    if (ready == null) {
      return const ScanVerdict.reject(
        title: 'Order not found',
        message: 'Please ask at the counter',
      );
    }
    if (_collected.contains(order)) {
      return ScanVerdict.warn(
        title: 'Already collected',
        message: 'Locker ${ready.locker} was opened before',
      );
    }
    // Your code: open the locker.
    _collected.add(order);
    return ScanVerdict.accept(
      title: 'Hello, ${ready.name}!',
      message: 'Your order is in locker ${ready.locker}',
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: BarcodeScanner(
      template: ScannerTemplate.kiosk(
        title: 'Pick up your order',
        hint: 'Hold the QR code from your e-mail up to the camera',
        check: _check,
        // Long enough to read the locker number from a step away.
        resumeAfter: const Duration(seconds: 5),
        // No buttons: staff leave with a long press in the top-left corner.
        hiddenExit: true,
      ),
    ),
  );
}

Pick one of many ​

Several codes in view, tap the one you need.

Try it in the demo

pick_one.dart
dart
// Pick one of many: a shipping label or a box carries several barcodes;
// every code in view gets a label and a tap picks the one the app needs.
// Try it on any parcel label. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class PickOnePage extends StatefulWidget {
  const PickOnePage({super.key});

  @override
  State<PickOnePage> createState() => _PickOnePageState();
}

class _PickOnePageState extends State<PickOnePage> {
  Barcode? _picked;

  Future<void> _pick() async {
    // The picked code comes back as the result; null when closed.
    final Barcode? barcode = await scanBarcode(
      context,
      template: const ScannerTemplate.pick(
        title: 'Tap the tracking number',
        // Linear codes only: the QR code of the carrier's app stays out.
        formats: BarcodeFormat.linear,
      ),
    );
    if (barcode == null || !mounted) return;
    // Your code: look the parcel up by its tracking number.
    setState(() => _picked = barcode);
  }

  @override
  Widget build(BuildContext context) {
    final Barcode? picked = _picked;
    return Scaffold(
      appBar: AppBar(title: const Text('Track a parcel')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (picked != null) ...[
                Text(picked.format.displayName),
                const SizedBox(height: 8),
                SelectableText(
                  picked.text,
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 24),
              ],
              FilledButton.icon(
                onPressed: _pick,
                icon: const Icon(Icons.touch_app_outlined),
                label: Text(picked == null ? 'Scan the label' : 'Pick another'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Read from a photo ​

A screenshot or a picture from the gallery.

Try it in the demo

read_from_photo.dart
dart
// Read from a photo: the user picks a screenshot or a picture from the
// gallery and the app lists every code in it, without a camera. Android,
// iOS, macOS, the web. Also needs image_picker.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:image_picker/image_picker.dart';

class ReadFromPhotoPage extends StatefulWidget {
  const ReadFromPhotoPage({super.key});

  @override
  State<ReadFromPhotoPage> createState() => _ReadFromPhotoPageState();
}

class _ReadFromPhotoPageState extends State<ReadFromPhotoPage> {
  List<Barcode>? _barcodes; // null until a photo is read
  String? _error;
  bool _reading = false;

  Future<void> _pick() async {
    final XFile? file = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    if (file == null || !mounted) return; // cancelled
    setState(() => _reading = true);
    List<Barcode>? barcodes;
    String? error;
    try {
      // Reads on a background isolate (a Web Worker on the web).
      barcodes = await const BarcodeReader().readAll(await file.readAsBytes());
    } on ImageDecodeException {
      error = 'This file is not an image';
    }
    if (!mounted) return;
    setState(() {
      _reading = false;
      _barcodes = barcodes;
      _error = error;
    });
  }

  @override
  Widget build(BuildContext context) {
    final List<Barcode>? barcodes = _barcodes;
    return Scaffold(
      appBar: AppBar(title: const Text('Read from a photo')),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _reading ? null : _pick,
        icon: const Icon(Icons.photo_library_outlined),
        label: const Text('Pick a photo'),
      ),
      body: switch ((_reading, _error, barcodes)) {
        (true, _, _) => const Center(child: CircularProgressIndicator()),
        (_, final String error, _) => Center(child: Text(error)),
        (_, _, null) => const Center(child: Text('Pick a photo with a code')),
        // "Not found" is an empty list, not an exception.
        (_, _, []) => const Center(child: Text('No code found in this photo')),
        (_, _, final List<Barcode> found) => ListView.separated(
          padding: const EdgeInsets.only(bottom: 96),
          itemCount: found.length,
          separatorBuilder: (_, _) => const Divider(height: 1),
          itemBuilder: (context, i) => ListTile(
            leading: const Icon(Icons.qr_code_2),
            title: SelectableText(found[i].text),
            subtitle: Text(found[i].format.displayName),
          ),
        ),
      },
    );
  }
}

Add a 2FA account ​

An otpauth:// code into your authenticator.

Try it in the demo

add_2fa.dart
dart
// Add a 2FA account: an authenticator app scans the otpauth:// QR code a
// service shows when two-factor sign-in is turned on, and keeps the
// account. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class AddTwoFactorPage extends StatefulWidget {
  const AddTwoFactorPage({super.key});

  @override
  State<AddTwoFactorPage> createState() => _AddTwoFactorPageState();
}

class _AddTwoFactorPageState extends State<AddTwoFactorPage> {
  OtpContent? _account;

  Future<void> _scan() async {
    // Any other code keeps the scanner open with the reject message.
    final OtpContent? otp = await scanContent<OtpContent>(
      context,
      formats: {BarcodeFormat.qrCode},
      hint: 'Scan the QR code from the service’s 2FA settings',
      reject: const ScanVerdict.reject(
        title: 'Not a 2FA code',
        message: 'Look for the code that starts two-factor sign-in.',
      ),
    );
    if (otp == null || !mounted) return; // closed
    // Your code: keep otp.secret in secure storage, such as the Keychain.
    setState(() => _account = otp);
  }

  @override
  Widget build(BuildContext context) {
    final OtpContent? account = _account;
    return Scaffold(
      appBar: AppBar(title: const Text('Add a 2FA account')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (account != null) ...[
                _AccountCard(account),
                const SizedBox(height: 24),
              ],
              FilledButton.icon(
                onPressed: _scan,
                icon: const Icon(Icons.qr_code_scanner),
                label: Text(account == null ? 'Add an account' : 'Add another'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _AccountCard extends StatelessWidget {
  const _AccountCard(this.otp);

  final OtpContent otp;

  @override
  Widget build(BuildContext context) {
    // The secret signs the user in: show only its end, to tell accounts
    // apart.
    final String secret = otp.secret;
    final String hint = secret.length > 4
        ? '•••• ${secret.substring(secret.length - 4)}'
        : '••••';
    final String timing = otp.type == OtpType.totp
        ? 'every ${otp.period} s'
        : 'counter ${otp.counter}';
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.verified_user_outlined, size: 40),
            const SizedBox(height: 8),
            Text(
              'Account added',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 8),
            Text(otp.issuer ?? 'Unknown service'),
            Text(otp.account),
            const SizedBox(height: 8),
            Text(
              '${otp.digits} digits $timing, '
              '${otp.algorithm.name.toUpperCase()} · secret $hint',
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ],
        ),
      ),
    );
  }
}

Creating codes ​

My profile QR code ​

A styled QR code of a profile link, shared as an image.

Try it in the demo

profile_qr.dart
dart
// My profile QR code: a styled QR code of a profile or referral link, on
// screen and shared as a PNG in the same style. Android, iOS, macOS, the
// web. Also needs share_plus.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:share_plus/share_plus.dart';

class ProfileQrPage extends StatelessWidget {
  const ProfileQrPage({super.key});

  // Your code: the signed-in user's link.
  static const String _link = 'https://example.com/u/anna';

  static const BarcodeStyle _style = BarcodeStyle(
    gradient: LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [Color(0xFF7C3AED), Color(0xFF2563EB)],
    ),
    moduleShape: ModuleShape.rounded,
    finderShape: FinderShape.rounded,
    caption: BarcodeCaption('@anna'),
    card: BarcodeCard(color: Colors.white, elevation: 6),
  );

  Future<void> _share(BuildContext context) async {
    final box = context.findRenderObject() as RenderBox?;
    // The same look as on screen, sharp at 1024 px.
    final png = await _style.encodePng(_link, size: 1024);
    await SharePlus.instance.share(
      ShareParams(
        files: [XFile.fromData(png, mimeType: 'image/png')],
        fileNameOverrides: ['my-qr.png'],
        // Where the share sheet points from on iPad.
        sharePositionOrigin: box == null
            ? null
            : box.localToGlobal(Offset.zero) & box.size,
      ),
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('My QR code')),
    body: Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const BarcodeView(_link, style: _style, width: 260),
          const SizedBox(height: 16),
          const Text('Scan to follow me'),
          const SizedBox(height: 24),
          Builder(
            builder: (context) => FilledButton.icon(
              onPressed: () => _share(context),
              icon: const Icon(Icons.ios_share),
              label: const Text('Share as an image'),
            ),
          ),
        ],
      ),
    ),
  );
}

A ticket in the app ​

A ticket card with the code the door scans.

Try it in the demo

ticket_card.dart
dart
// A ticket in the app: an event ticket card with the code the door scans,
// as a QR code, Aztec (airlines, railways), PDF417 or a Code 128 barcode
// for older laser scanners. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class TicketCardPage extends StatefulWidget {
  const TicketCardPage({super.key});

  @override
  State<TicketCardPage> createState() => _TicketCardPageState();
}

class _TicketCardPageState extends State<TicketCardPage> {
  // Your code: the ticket from your server.
  static const String _event = 'Spring Jazz Night';
  static const String _date = 'Sat, 14 March · 19:30';
  static const String _seat = 'Row F · Seat 12';
  static const String _ticket = 'TICKET-1002';

  BarcodeFormat _format = BarcodeFormat.qrCode;

  @override
  Widget build(BuildContext context) {
    final TextTheme text = Theme.of(context).textTheme;
    // Tip: a door scanner reads a phone screen best at full brightness;
    // raise it while the ticket is open (for example with the
    // screen_brightness package) and restore it when the page closes.
    final bool linear = _format == BarcodeFormat.code128;
    return Scaffold(
      appBar: AppBar(title: const Text('My ticket')),
      body: ListView(
        padding: const EdgeInsets.all(24),
        children: [
          Card(
            clipBehavior: Clip.antiAlias,
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  color: Theme.of(context).colorScheme.primaryContainer,
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(_event, style: text.headlineSmall),
                      const SizedBox(height: 4),
                      const Text(_date),
                      const Text(_seat),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(24),
                  // The code stays black on white: a door scanner reads
                  // contrast, not colours.
                  child: BarcodeView(
                    _ticket,
                    writer: BarcodeWriter(_format),
                    width: linear ? 280 : 220,
                    height: linear ? 110 : null,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 20),
                  child: Text(_ticket, style: text.labelLarge),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
          SegmentedButton<BarcodeFormat>(
            segments: const [
              ButtonSegment(value: BarcodeFormat.qrCode, label: Text('QR')),
              ButtonSegment(value: BarcodeFormat.aztec, label: Text('Aztec')),
              ButtonSegment(value: BarcodeFormat.pdf417, label: Text('PDF417')),
              ButtonSegment(value: BarcodeFormat.code128, label: Text('128')),
            ],
            selected: {_format},
            onSelectionChanged: (s) => setState(() => _format = s.first),
          ),
        ],
      ),
    );
  }
}

Wi‑Fi card for guests ​

A QR code that joins the network, to print or share.

Try it in the demo

wifi_for_guests.dart
dart
// A Wi-Fi card for guests: the network and its password as a QR code that
// phones join from the camera, shared as PNG or SVG to print and put on
// the wall. Android, iOS, macOS, the web. Also needs share_plus.
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:share_plus/share_plus.dart';

class WifiForGuestsPage extends StatefulWidget {
  const WifiForGuestsPage({super.key});

  @override
  State<WifiForGuestsPage> createState() => _WifiForGuestsPageState();
}

class _WifiForGuestsPageState extends State<WifiForGuestsPage> {
  final _ssid = TextEditingController(text: 'Cafe Lumen Guests');
  final _password = TextEditingController(text: 'espresso2027');
  WifiSecurity _security = WifiSecurity.wpa;

  WifiContent get _wifi => WifiContent(
    ssid: _ssid.text,
    password: _security == WifiSecurity.none ? null : _password.text,
    security: _security,
  );

  BarcodeStyle get _style => BarcodeStyle.soft.copyWith(
    title: () => const BarcodeCaption('Free Wi‑Fi'),
    caption: () => BarcodeCaption('${_ssid.text}\nScan to join'),
    card: () => const BarcodeCard(color: Colors.white),
  );

  @override
  void dispose() {
    _ssid.dispose();
    _password.dispose();
    super.dispose();
  }

  Future<void> _share(BuildContext context, {required bool svg}) async {
    final box = context.findRenderObject() as RenderBox?;
    final String data = _wifi.toPayload();
    // The same card as on screen; SVG prints sharp at any size.
    final XFile file = svg
        ? XFile.fromData(
            utf8.encode(await _style.encodeSvg(data)),
            mimeType: 'image/svg+xml',
          )
        : XFile.fromData(
            await _style.encodePng(data, size: 2048),
            mimeType: 'image/png',
          );
    await SharePlus.instance.share(
      ShareParams(
        files: [file],
        fileNameOverrides: [svg ? 'wifi.svg' : 'wifi.png'],
        sharePositionOrigin: box == null
            ? null
            : box.localToGlobal(Offset.zero) & box.size,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // What keeps the network from being built: an empty name, a short
    // WPA password…
    final bool valid = _wifi.validate().isEmpty;
    return Scaffold(
      appBar: AppBar(title: const Text('Wi‑Fi for guests')),
      body: ListView(
        padding: const EdgeInsets.all(24),
        children: [
          TextField(
            controller: _ssid,
            decoration: const InputDecoration(labelText: 'Network name'),
            onChanged: (_) => setState(() {}),
          ),
          const SizedBox(height: 12),
          SegmentedButton<WifiSecurity>(
            segments: const [
              ButtonSegment(value: WifiSecurity.wpa, label: Text('WPA/WPA2')),
              ButtonSegment(value: WifiSecurity.wpa3, label: Text('WPA3')),
              ButtonSegment(value: WifiSecurity.none, label: Text('Open')),
            ],
            selected: {_security},
            onSelectionChanged: (s) => setState(() => _security = s.first),
          ),
          if (_security != WifiSecurity.none)
            TextField(
              controller: _password,
              decoration: const InputDecoration(labelText: 'Password'),
              onChanged: (_) => setState(() {}),
            ),
          const SizedBox(height: 24),
          Center(
            // Shows what is wrong instead of a code that cannot join.
            child: BarcodeContentView(
              _wifi,
              style: _style,
              width: 260,
              errorBuilder: (context, error) => Text(error.message),
            ),
          ),
          if (valid) ...[
            const SizedBox(height: 24),
            Builder(
              builder: (context) => Wrap(
                alignment: WrapAlignment.center,
                spacing: 12,
                children: [
                  FilledButton.icon(
                    onPressed: () => _share(context, svg: false),
                    icon: const Icon(Icons.ios_share),
                    label: const Text('Share PNG'),
                  ),
                  OutlinedButton.icon(
                    onPressed: () => _share(context, svg: true),
                    icon: const Icon(Icons.print_outlined),
                    label: const Text('Share SVG to print'),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
}

A QR code on an invoice ​

A SEPA or Swiss QR-bill payment code.

Try it in the demo

invoice_qr.dart
dart
// A QR code on an invoice: the customer's banking app scans it and fills
// in the transfer. A SEPA credit transfer (EPC, "GiroCode") in the euro
// area, or a Swiss QR-bill. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class InvoiceQrPage extends StatefulWidget {
  const InvoiceQrPage({super.key});

  @override
  State<InvoiceQrPage> createState() => _InvoiceQrPageState();
}

enum _Standard { sepa, swiss }

class _InvoiceQrPageState extends State<InvoiceQrPage> {
  // Your code: the invoice from your billing system.
  static const String _number = 'Invoice 2027-0042';
  static const String _amount = '1949.75'; // main unit, two decimals

  static const EpcPaymentContent _sepa = EpcPaymentContent(
    name: 'Kaffeehaus Lumen GmbH',
    iban: 'DE89370400440532013000',
    amount: _amount,
    creditorReference: 'RF18539007547034', // ISO 11649, checked
  );

  static const SwissQrBillContent _swiss = SwissQrBillContent(
    iban: 'CH4431999123000889012', // a QR-IBAN takes a QR reference
    creditor: SwissAddress(
      name: 'Robert Schneider AG',
      street: 'Rue du Lac',
      buildingNumber: '1268',
      postalCode: '2501',
      town: 'Biel',
      country: 'CH',
    ),
    amount: _amount,
    creditorReference: '210000000003139471430009017',
    message: _number,
  );

  _Standard _standard = _Standard.sepa;

  @override
  Widget build(BuildContext context) {
    final PaymentContent payment = switch (_standard) {
      _Standard.sepa => _sepa,
      _Standard.swiss => _swiss,
    };
    final ScannerLocalizations texts = ScannerLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(title: const Text(_number)),
      body: ListView(
        padding: const EdgeInsets.all(24),
        children: [
          SegmentedButton<_Standard>(
            segments: const [
              ButtonSegment(value: _Standard.sepa, label: Text('SEPA')),
              ButtonSegment(value: _Standard.swiss, label: Text('QR-bill')),
            ],
            selected: {_standard},
            onSelectionChanged: (s) => setState(() => _standard = s.first),
          ),
          const SizedBox(height: 24),
          Center(
            // What each standard asks for: a QR-bill carries the Swiss
            // cross (on paper the code is 46 × 46 mm), both use error
            // correction M.
            child: BarcodeContentView(payment, width: 220),
          ),
          const SizedBox(height: 24),
          // The same five fields whatever the standard.
          ListTile(
            title: const Text('Pay to'),
            subtitle: Text(payment.payee ?? '—'),
          ),
          ListTile(
            title: const Text('Account'),
            subtitle: Text(payment.account ?? '—'),
          ),
          ListTile(
            title: const Text('Amount'),
            // "1949.75 EUR" in the scanner's language, "Any amount" without one.
            subtitle: Text(texts.amountOf(payment.amount, payment.currency)),
          ),
          ListTile(
            title: const Text('Reference'),
            subtitle: Text(payment.reference ?? '—'),
          ),
        ],
      ),
    );
  }
}

A sheet of labels ​

Many codes on an A4 page in columns, as SVG for print.

Try it in the demo

label_sheet.dart
dart
// A sheet of labels: 1000 numbered codes, AA000001 to AA001000, on A4
// pages, shared as one PDF to print at 100 %. Android, iOS, macOS, the web.
// Also needs share_plus. The full sheet editor (a list or a CSV column,
// paper, code size, SVG and ZIP) is in the demo's Create → Many codes.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:share_plus/share_plus.dart';

class LabelSheetPage extends StatefulWidget {
  const LabelSheetPage({super.key});

  @override
  State<LabelSheetPage> createState() => _LabelSheetPageState();
}

class _LabelSheetPageState extends State<LabelSheetPage> {
  // Your codes: made one when asked for, so 1000 or 100 000 cost nothing.
  final SerialItems _items = SerialItems('AA{n:6}', count: 1000);

  // Match your label paper: page size, labels across and down, margins.
  static const BarcodeLabelSheet _sheet = BarcodeLabelSheet(
    paper: PaperSize.a4,
    columns: 3,
    rows: 8,
    codeSize: 25, // millimetres
    style: BarcodeStyle.soft,
  );

  int _page = 0;
  double? _progress; // while making the PDF

  Future<void> _share(BuildContext context) async {
    final box = context.findRenderObject() as RenderBox?;
    final messenger = ScaffoldMessenger.of(context);
    setState(() => _progress = 0);
    try {
      // Encoded a page at a time, off the UI thread.
      final pdf = await _sheet.pdf(
        _items,
        onProgress: (done, total) {
          if (mounted) setState(() => _progress = done / total);
        },
      );
      await SharePlus.instance.share(
        ShareParams(
          files: [XFile.fromData(pdf, mimeType: 'application/pdf')],
          fileNameOverrides: ['labels.pdf'],
          sharePositionOrigin: box == null
              ? null
              : box.localToGlobal(Offset.zero) & box.size,
        ),
      );
    } on BarcodeWriteException catch (e) {
      // It names the item that cannot be encoded.
      messenger.showSnackBar(SnackBar(content: Text(e.message)));
    } finally {
      if (mounted) setState(() => _progress = null);
    }
  }

  @override
  Widget build(BuildContext context) {
    final int pages = _sheet.pageCount(_items.length);
    return Scaffold(
      appBar: AppBar(title: const Text('A sheet of labels')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Row(
            children: [
              IconButton(
                onPressed: _page > 0 ? () => setState(() => _page--) : null,
                icon: const Icon(Icons.chevron_left),
              ),
              Expanded(
                child: Text(
                  'Page ${_page + 1} of $pages',
                  textAlign: TextAlign.center,
                ),
              ),
              IconButton(
                onPressed: _page < pages - 1
                    ? () => setState(() => _page++)
                    : null,
                icon: const Icon(Icons.chevron_right),
              ),
            ],
          ),
          // The page as the PDF prints it.
          DecoratedBox(
            decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
            child: BarcodeLabelSheetView(
              sheet: _sheet,
              items: _items,
              page: _page,
            ),
          ),
          const SizedBox(height: 16),
          Builder(
            builder: (context) => FilledButton.icon(
              onPressed: _progress != null ? null : () => _share(context),
              icon: const Icon(Icons.print_outlined),
              label: Text(
                _progress == null
                    ? 'Share as PDF'
                    : 'Making the pages… ${(_progress! * 100).round()} %',
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Business card ​

A vCard QR code that saves your contact.

Try it in the demo

business_card.dart
dart
// A business card: a vCard QR code that any phone camera offers to save as
// a contact, for a conference badge, an e-mail signature or the "share my
// contact" screen of an app. Android, iOS, macOS, the web.
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';

class BusinessCardPage extends StatelessWidget {
  const BusinessCardPage({super.key});

  // Your code: the user's profile.
  static final ContactContent _contact = ContactContent(
    name: 'Anna Petrova',
    organization: 'Lumen Labs',
    title: 'Product designer',
    phones: const ['+374 91 234567'],
    emails: const ['anna@lumenlabs.example'],
    urls: [Uri.parse('https://lumenlabs.example')],
  );

  @override
  Widget build(BuildContext context) {
    final TextTheme text = Theme.of(context).textTheme;
    final ColorScheme colors = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Business card')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(_contact.name!, style: text.headlineSmall),
                  Text(
                    '${_contact.title}, ${_contact.organization}',
                    style: text.bodyMedium?.copyWith(color: colors.primary),
                  ),
                  const SizedBox(height: 16),
                  // A vCard 3.0. For a smaller code with fewer fields:
                  // BarcodeView(_contact.toPayload(format: ContactFormat.meCard)).
                  BarcodeContentView(
                    _contact,
                    style: BarcodeStyle.soft,
                    width: 220,
                  ),
                  const SizedBox(height: 8),
                  Text('Scan to save my contact', style: text.bodySmall),
                  const SizedBox(height: 16),
                  for (final String line in [
                    ..._contact.phones,
                    ..._contact.emails,
                    for (final Uri url in _contact.urls) url.host,
                  ])
                    Text(line),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}