You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter扫码问题:指定格式条形码扫描及扫码类型控制

Flutter 扫码格式控制解决方案

1. 扫描指定格式的条形码

在Flutter中,主流扫码包都支持指定识别格式,以下是两款常用包的实现方式:

使用barcode_scan2包

先在pubspec.yaml添加依赖:

dependencies:
  barcode_scan2: ^4.2.0

调用扫描时通过restrictFormat参数指定目标格式,例如仅识别CODE_128和EAN_13:

import 'package:barcode_scan2/barcode_scan2.dart';

Future<void> scanSpecificBarcode() async {
  try {
    final result = await BarcodeScanner.scan(
      options: ScanOptions(
        restrictFormat: [BarcodeFormat.code128, BarcodeFormat.ean13],
        useCamera: -1, // 使用默认相机
      ),
    );
    print('扫描结果:${result.rawContent}');
  } catch (e) {
    print('扫描出错:$e');
  }
}

使用flutter_barcode_scanner包

添加依赖:

dependencies:
  flutter_barcode_scanner: ^2.0.0

通过barcodeFormat或ScanMode参数限定格式:

import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

Future<void> scanSpecificFormat() async {
  String barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
    '#ff6666', // 扫描线颜色
    '取消', // 取消按钮文字
    true, // 是否显示闪光灯按钮
    ScanMode.BARCODE, // 限定为条形码模式,也可配合具体格式枚举(参考包文档)
  );
  print('扫描结果:$barcodeScanRes');
}

2. 仅识别条形码/仅识别二维码

仅识别条形码(禁用二维码)

基于barcode_scan2实现

仅保留条形码相关格式,排除二维码格式:

Future<void> scanOnlyBarcode() async {
  try {
    final result = await BarcodeScanner.scan(
      options: ScanOptions(
        restrictFormat: [
          BarcodeFormat.code128,
          BarcodeFormat.ean8,
          BarcodeFormat.ean13,
          BarcodeFormat.upcA,
          BarcodeFormat.upcE,
          // 添加其他需要的条形码格式
        ],
      ),
    );
    print('条形码结果:${result.rawContent}');
  } catch (e) {
    print('扫描出错:$e');
  }
}

基于flutter_barcode_scanner实现

直接指定ScanMode.BARCODE模式,自动忽略二维码:

Future<void> scanOnlyBarcode() async {
  String scanResult = await FlutterBarcodeScanner.scanBarcode(
    '#FF0000',
    '取消',
    true,
    ScanMode.BARCODE,
  );
  print('条形码结果:$scanResult');
}

仅识别二维码(禁用条形码)

基于barcode_scan2实现

仅指定QR_CODE格式:

Future<void> scanOnlyQrCode() async {
  try {
    final result = await BarcodeScanner.scan(
      options: ScanOptions(
        restrictFormat: [BarcodeFormat.qrCode],
      ),
    );
    print('二维码结果:${result.rawContent}');
  } catch (e) {
    print('扫描出错:$e');
  }
}

基于flutter_barcode_scanner实现

指定ScanMode.QR模式:

Future<void> scanOnlyQrCode() async {
  String scanResult = await FlutterBarcodeScanner.scanBarcode(
    '#FF0000',
    '取消',
    true,
    ScanMode.QR,
  );
  print('二维码结果:$scanResult');
}

注意:不同包的格式枚举名称可能略有差异,使用前请确认对应包的文档说明。

内容的提问来源于stack exchange,提问作者Vikas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:40:37