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

Flutter中mobile_scanner包实现指定区域条码/二维码扫描方案

实现mobile_scanner指定区域识别条码(不替换包)

因为mobile_scanner原生不支持指定检测区域,我们可以通过在识别回调中校验条码位置的方式实现需求:只处理位于你添加的qrFrame区域内的条码,其他区域的识别结果直接忽略。

步骤1:添加GlobalKey获取检测区域的屏幕坐标

给中间的二维码框Image添加GlobalKey,用来获取它在屏幕上的实际位置和尺寸:

final GlobalKey _frameKey = GlobalKey();

步骤2:在onDetect中校验条码位置

在onDetect回调里,先获取检测区域的Rect,再判断识别到的条码是否落在该区域内,只有符合条件才执行后续逻辑:

  • 通过_frameKey获取Image的RenderBox,计算出它的屏幕坐标和范围
  • 利用args.barcodes拿到条码的边界框(bounding box),判断是否与检测区域有交集(或完全包含)

完整修改后的代码

final GlobalKey _frameKey = GlobalKey();

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      children: [
        MobileScanner(
          allowDuplicates: false,
          controller: cameraController,
          onDetect: (qrcode, args) {
            if (qrcode.rawValue == null) {
              debugPrint('Failed to scan Barcode');
              return;
            }

            // 获取检测区域的屏幕Rect
            final RenderBox? frameBox = _frameKey.currentContext?.findRenderObject() as RenderBox?;
            if (frameBox == null) return;
            final frameRect = frameBox.localToGlobal(Offset.zero) & frameBox.size;

            // 遍历所有识别到的条码,判断是否在检测区域内
            bool isInTargetArea = false;
            for (final barcode in args.barcodes) {
              final barcodeRect = barcode.boundingBox;
              if (barcodeRect != null && frameRect.overlaps(barcodeRect)) {
                isInTargetArea = true;
                break;
              }
            }

            // 只有在指定区域内的条码才处理
            if (isInTargetArea) {
              final String code = qrcode.rawValue!;
              Get.off(QrInfo(codeInfo: code), binding: QrCodeBinding());
              debugPrint('Qr found! $code');
            }
          },
        ),
        Center(
          child: Image.asset(
            'assets/qrFrame.png',
            scale: 0.25,
            color: Colors.red,
            key: _frameKey, // 绑定GlobalKey
          ),
        ),
      ],
    ),
  );
}

补充说明

  • frameRect.overlaps(barcodeRect):判断条码的边界框和检测区域是否有重叠,如果你需要条码完全在区域内,可以改用frameRect.contains(barcodeRect.center)(判断条码中心是否在区域内)或者frameRect.contains(barcodeRect)(条码完全在区域内),根据你的需求调整。
  • 注意处理frameBox为空的情况(比如组件还没渲染完成时),避免空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:30:50