Skip to main content

flutter_card_scanner_plus 0.6.0-beta.1 copy "flutter_card_scanner_plus: ^0.6.0-beta.1" to clipboard
flutter_card_scanner_plus: ^0.6.0-beta.1 copied to clipboard

On-device bank card scanner for iOS, Android, macOS, Windows and the web (Visa, Mastercard, Amex, Discover, JCB, Diners, UnionPay). Native OCR, no third-party camera plugin required.

example/lib/main.dart

import 'dart:async';

import 'package:flutter/foundation.dart'
    show TargetPlatform, defaultTargetPlatform, kIsWeb;
// Deprecated by Flutter 3.50 for package:material_ui. Kept until the
// package itself moves: see lib/src/ui/card_scanner_page.dart.
// ignore: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:flutter_card_scanner_plus/flutter_card_scanner_plus.dart';
import 'package:image_picker/image_picker.dart';
import 'package:url_launcher/url_launcher.dart';

void main() => runApp(const ExampleApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Card Scanner Example',
      theme: ThemeData(colorSchemeSeed: Colors.indigo, useMaterial3: true),
      home: const HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  CardScanResult? _result;

  /// Which build of the browser engine the last scan loaded. Always
  /// `null` on a phone, where the system's own engine does the reading.
  OcrEngineReport? _engine;
  StreamSubscription<OcrEngineReport>? _engineReports;

  /// Empty everywhere but macOS, where a Mac has several cameras and no
  /// obviously right one. The picker below appears only when there is
  /// something to pick.
  List<CameraDescription> _cameras = const [];
  String? _cameraId;

  /// Every line the engine read in the richest frame of the last scan.
  ///
  /// A wrong field is nearly always a line nobody would guess from the
  /// result alone: the name heuristic has no structural marker to go by,
  /// so printed card art that is shaped like a name wins. Showing the raw
  /// lines is the difference between "the scanner is broken" and "the
  /// card says that".
  List<TextLine> _lines = const [];

  @override
  void initState() {
    super.initState();
    _engineReports = CardScanner.engineReports.listen((report) {
      debugPrint('$report');
      if (mounted) setState(() => _engine = report);
    });
    _loadCameras();
  }

  @override
  void dispose() {
    _engineReports?.cancel();
    super.dispose();
  }

  Future<void> _loadCameras() async {
    final cameras = await CardScannerPlatform.instance.listCameras();
    if (!mounted || cameras.isEmpty) return;
    // The list is ranked, so the first is the one the plugin would have
    // opened anyway.
    setState(() {
      _cameras = cameras;
      _cameraId = cameras.first.id;
    });
  }

  Future<void> _scan({
    required ScanRequirements requirements,
    bool enableHaptics = false,
  }) async {
    // The page owns its controller, so the frames are read from the
    // platform directly. The richest frame is kept rather than the last:
    // the final one is often a corner of the card on its way out.
    var fullest = const <TextLine>[];
    final frames = CardScannerPlatform.instance.frames.listen((frame) {
      if (frame.lines.length > fullest.length) fullest = frame.lines;
    });
    final result = await CardScannerPage.show(
      context,
      requirements: requirements,
      title: 'Scan card',
      cameraId: _cameraId,
      enableHaptics: enableHaptics,
      onOpenSettings: _openSettings,
    );
    await frames.cancel();
    if (!mounted) return;
    setState(() {
      _result = result;
      _lines = fullest;
    });
  }

  /// A denied camera is a dead end until the user changes it in the
  /// system settings, so the button has to land them there. macOS has no
  /// permission_handler support for this pane, so the example opens it by
  /// URL; a real app on iOS or Android calls openAppSettings instead.
  Future<void> _openSettings() async {
    if (!kIsWeb && defaultTargetPlatform == TargetPlatform.macOS) {
      final opened = await launchUrl(
        Uri.parse(
          'x-apple.systempreferences:com.apple.preference.security'
          '?Privacy_Camera',
        ),
      );
      if (opened) return;
    }
    if (!mounted) return;
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('Open the app settings here')));
  }

  Future<void> _scanPhoto() async {
    final file = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (file == null) return;
    final bytes = await file.readAsBytes();
    try {
      final result = await CardScanner.scanImage(
        bytes,
        requirements: ScanRequirements.full,
      );
      if (!mounted) return;
      // Nothing here exposes the lines, and last scan's would be a lie.
      setState(() {
        _result = result;
        _lines = const [];
      });
    } on CardScannerException catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
    }
  }

  /// One line saying which engine ran and how it went.
  static String _describe(OcrEngineReport report) {
    final name = switch (report.backend) {
      OcrBackend.webGpu => 'WebGPU',
      OcrBackend.wasm => 'WebAssembly',
    };
    final benchmark = report.benchmark;
    final loadTime = report.loadTime;
    return [
      'Engine: $name',
      if (loadTime != null) 'loaded in ${loadTime.inMilliseconds} ms',
      if (benchmark != null) 'benchmark ${benchmark.inMilliseconds} ms',
      if (report.tooSlow) 'too slow to scan',
      if (report.webGpuFailure != null) 'WebGPU was not usable',
    ].join(', ');
  }

  @override
  Widget build(BuildContext context) {
    final r = _result;
    final engine = _engine;
    // The engine returns lines unordered; reading order makes the dump
    // comparable with the card in your hand.
    final lines = [..._lines]
      ..sort((a, b) {
        final byTop = a.box.top.compareTo(b.box.top);
        return byTop != 0 ? byTop : a.box.left.compareTo(b.box.left);
      });
    return Scaffold(
      appBar: AppBar(title: const Text('flutter_card_scanner_plus')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            if (_cameras.isNotEmpty) ...[
              DropdownButtonFormField<String>(
                initialValue: _cameraId,
                decoration: const InputDecoration(
                  labelText: 'Camera',
                  border: OutlineInputBorder(),
                ),
                items: [
                  for (final camera in _cameras)
                    DropdownMenuItem(
                      value: camera.id,
                      child: Text('${camera.name} · ${camera.kind.name}'),
                    ),
                ],
                onChanged: (id) => setState(() => _cameraId = id),
              ),
              const SizedBox(height: 16),
            ],
            FilledButton.icon(
              // A browser reads about one frame a second rather than
              // eight, so it votes on fewer of them.
              onPressed: () => _scan(
                requirements: kIsWeb
                    ? ScanRequirements.web
                    : ScanRequirements.standard,
              ),
              icon: const Icon(Icons.credit_card),
              label: const Text('Scan (number + expiry, name if quick)'),
            ),
            const SizedBox(height: 12),
            OutlinedButton.icon(
              onPressed: () => _scan(requirements: ScanRequirements.numberOnly),
              icon: const Icon(Icons.pin_outlined),
              label: const Text('Scan number only'),
            ),
            const SizedBox(height: 12),
            OutlinedButton.icon(
              onPressed: () => _scan(requirements: ScanRequirements.full),
              icon: const Icon(Icons.badge_outlined),
              label: const Text('Scan all three (wait for name)'),
            ),
            const SizedBox(height: 12),
            OutlinedButton.icon(
              onPressed: () => _scan(
                requirements: ScanRequirements.twoSided,
                enableHaptics: true,
              ),
              icon: const Icon(Icons.flip_to_back_outlined),
              label: const Text('Scan a two-sided card'),
            ),
            const SizedBox(height: 12),
            OutlinedButton.icon(
              onPressed: () => Navigator.of(context).push(
                MaterialPageRoute<void>(
                  builder: (_) => const CustomOverlayPage(),
                ),
              ),
              icon: const Icon(Icons.brush_outlined),
              label: const Text('Custom overlay'),
            ),
            const SizedBox(height: 12),
            OutlinedButton.icon(
              onPressed: _scanPhoto,
              icon: const Icon(Icons.photo_library_outlined),
              label: const Text('Scan from photo'),
            ),
            const SizedBox(height: 32),
            if (engine != null) ...[
              Text(
                _describe(engine),
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.bodySmall,
              ),
              const SizedBox(height: 12),
            ],
            if (r == null)
              const Text('No card scanned yet', textAlign: TextAlign.center)
            else
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        r.brand?.displayName ?? 'Unknown brand',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      const SizedBox(height: 8),
                      Text(
                        r.formattedNumber ?? '—',
                        style: const TextStyle(
                          fontSize: 22,
                          letterSpacing: 1.5,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        'Expiry: ${r.formattedExpiry ?? '—'}'
                        '${r.isExpired() ? '  (expired)' : ''}',
                      ),
                      Text('Name: ${r.cardholderName ?? '—'}'),
                      if (lines.isNotEmpty) ...[
                        const Divider(height: 24),
                        Text(
                          'OCR lines (${lines.length})',
                          style: Theme.of(context).textTheme.labelLarge,
                        ),
                        const SizedBox(height: 4),
                        for (final line in lines)
                          SelectableText(
                            '${(line.confidence * 100).round().toString().padLeft(3)}%  '
                            '${line.text}',
                            style: const TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 12,
                            ),
                          ),
                      ],
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

/// Shows how to draw your own UI over the preview with `overlayBuilder`.
class CustomOverlayPage extends StatefulWidget {
  const CustomOverlayPage({super.key});

  @override
  State<CustomOverlayPage> createState() => _CustomOverlayPageState();
}

class _CustomOverlayPageState extends State<CustomOverlayPage> {
  final _controller = CardScannerController(stopWhenComplete: false);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CardScannerView(
        controller: _controller,
        frameAlignment: Alignment.center,
        overlayBuilder: (context, state, cardRect) {
          final frame = state.lastFrame;
          return Stack(
            children: [
              Positioned.fromRect(
                rect: cardRect,
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: state.isComplete
                          ? Colors.greenAccent
                          : Colors.amber,
                      width: 2,
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
              ),
              Positioned(
                left: 16,
                right: 16,
                bottom: 48,
                child: Column(
                  children: [
                    _Chip('PAN', frame.pan?.number, state.result.number),
                    _Chip(
                      'EXP',
                      frame.expiry?.formatted,
                      state.result.formattedExpiry,
                    ),
                    _Chip(
                      'NAME',
                      frame.name?.name,
                      state.result.cardholderName,
                    ),
                    const SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        FilledButton(
                          onPressed: _controller.reset,
                          child: const Text('Reset'),
                        ),
                        const SizedBox(width: 12),
                        FilledButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: const Text('Close'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _Chip extends StatelessWidget {
  const _Chip(this.label, this.live, this.stable);

  final String label;
  final String? live;
  final String? stable;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          SizedBox(
            width: 56,
            child: Text(label, style: const TextStyle(color: Colors.white70)),
          ),
          Expanded(
            child: Text(
              stable ?? live ?? '…',
              style: TextStyle(
                color: stable != null ? Colors.greenAccent : Colors.white,
                fontFamily: 'monospace',
              ),
            ),
          ),
        ],
      ),
    );
  }
}
5
likes
150
points
1.89k
downloads

Documentation

API reference

Publisher

verified publisherapissystems.dev

Weekly Downloads

On-device bank card scanner for iOS, Android, macOS, Windows and the web (Visa, Mastercard, Amex, Discover, JCB, Diners, UnionPay). Native OCR, no third-party camera plugin required.

Repository (GitHub)
View/report issues

Topics

#camera #ocr #credit-card #payment #scanner

License

MIT (license)

Dependencies

flutter, meta, web

More

Packages that depend on flutter_card_scanner_plus

Packages that implement flutter_card_scanner_plus