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

Flutter使用mobile_scanner扫码后相机持续扫描致重复跳转问题求助

解决mobile_scanner扫码后重复跳转页面的问题

你当前的代码里,虽然设置了DetectionSpeed.noDuplicates,但扫码成功后没有停止相机扫描逻辑,即便开启去重,只要二维码一直出现在镜头前,onDetect回调还是会被持续触发,导致多次跳转结果页面。下面提供两种可行的解决方案:


方案一:扫码成功后立即停止扫描控制器

直接调用控制器的stop()方法终止扫码检测,从根源上避免重复触发回调:

// 先定义控制器实例
final MobileScannerController _scannerController = MobileScannerController(
  detectionSpeed: DetectionSpeed.noDuplicates,
);

// 在组件中使用
MobileScanner(
  controller: _scannerController,
  onDetect: (barcodes) {
    // 优先停止扫描
    _scannerController.stop();
    // 再执行页面跳转
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ResultScreen(),
      ),
    );
    print("QR Code Found!");
  },
)

如果之后需要恢复扫码功能,比如从结果页面返回后重新扫描,可以在页面的initState或者返回回调中调用_scannerController.start()。


方案二:用状态变量控制仅处理一次扫码

如果不想停止相机,只是希望单次扫码后不再触发跳转,可以添加布尔变量标记是否已处理过扫码结果:

// 在StatefulWidget的state类中定义状态变量
bool _hasScanned = false;

@override
Widget build(BuildContext context) {
  return MobileScanner(
    controller: MobileScannerController(
      detectionSpeed: DetectionSpeed.noDuplicates,
    ),
    onDetect: (barcodes) {
      // 仅当未扫描过时执行逻辑
      if (!_hasScanned) {
        _hasScanned = true;
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => ResultScreen(),
          ),
        ).then((_) {
          // 从结果页面返回时,重置标记允许再次扫码
          _hasScanned = false;
        });
        print("QR Code Found!");
      }
    },
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:42:38