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

Flutter使用flutter_barcode_scanner扫码后无法显示商品信息求助

Flutter条码扫描后无法匹配商品信息问题排查与解决

我在Flutter应用中使用flutter_barcode_scanner开发条码扫描功能,需求是扫描条码后从预定义的静态映射中获取对应商品信息并弹窗展示详情,但目前扫描后总是弹出“无匹配商品”的错误提示。

相关代码

import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

void main() {
  runApp(MaterialApp(
    home: BarcodeScannerScreen(),
  ));
}

class BarcodeScannerScreen extends StatefulWidget {
  @override
  _BarcodeScannerScreenState createState() => _BarcodeScannerScreenState();
}

class _BarcodeScannerScreenState extends State<BarcodeScannerScreen> {
  final Map<String, Map<String, dynamic>> staticItems = {
    "4523659874586": {
      "itemName": "Masala Masti",
      "itemDescription": "TooYum! Sticks",
      "itemPrice": 20,
    },
    "5263658978452": {
      "itemName": "Waffers",
      "itemDescription": "Balaji Salted Waffers",
      "itemPrice": 10,
    },
    "856363625635": {
      "itemName": "Amul Processed Cheese",
      "itemDescription": "Amul Processed Cheese 500 g",
      "itemPrice": 500,
    },
  };

  String _scannedBarcode = '';

  Future<void> _scanBarcode(BuildContext context) async {
    String barcode = await FlutterBarcodeScanner.scanBarcode(
      "#ff6666", // Scanner overlay color
      "Cancel", // Cancel button text
      true, // Show flash icon
      ScanMode.BARCODE, // Barcode scan mode
    );

    if (barcode != '-1') {
      setState(() {
        _scannedBarcode = barcode;
      });

      final item = staticItems[barcode];
      if (item != null) {
        _showProductPopup(context, item);
      } else {
        _showErrorPopup(context);
      }
    }
  }

  void _showProductPopup(BuildContext context, Map<String, dynamic> item) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(item['itemName']),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(item['itemDescription']),
              SizedBox(height: 10),
              Text('Price: \$${item['itemPrice'].toStringAsFixed(2)}'),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Close'),
            ),
          ],
        );
      },
    );
  }

  void _showErrorPopup(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Error'),
          content: Text('No matching item found for the scanned barcode.'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Close'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ScanShop - Barcode Scanner'),
        backgroundColor: Colors.teal,
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 40),
              ElevatedButton(
                onPressed: () => _scanBarcode(context),
                style: ElevatedButton.styleFrom(
                  primary: Colors.teal,
                  onPrimary: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 40, vertical: 16),
                  elevation: 5,
                  shadowColor: Colors.grey.withOpacity(0.5),
                ),
                child: Text(
                  'Scan Barcode',
                  style: TextStyle(fontSize: 18),
                ),
              ),
              SizedBox(height: 40),
              if (_scannedBarcode.isNotEmpty)
                Text(
                  'Scanned Barcode: $_scannedBarcode',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

应用错误截图

应用错误截图


问题原因与解决方案

核心原因

扫描得到的条码字符串大概率带有首尾空白字符(空格、换行符等),导致和静态映射里的纯数字key无法匹配。

解决步骤

  1. 清洗扫描结果
    在_scanBarcode方法中,对返回的条码字符串做trim处理,去除首尾空白:

    Future<void> _scanBarcode(BuildContext context) async {
      String barcode = await FlutterBarcodeScanner.scanBarcode(
        "#ff6666",
        "Cancel",
        true,
        ScanMode.BARCODE,
      );
    
      // 添加这行,清洗条码
      barcode = barcode.trim();
    
      if (barcode != '-1') {
        setState(() {
          _scannedBarcode = barcode;
        });
    
        final item = staticItems[barcode];
        if (item != null) {
          _showProductPopup(context, item);
        } else {
          _showErrorPopup(context);
        }
      }
    }
    
  2. 调试验证(可选)
    可以添加打印语句,确认扫描到的原始条码内容,方便排查其他格式问题:

    setState(() {
      _scannedBarcode = barcode;
    });
    // 打印带引号,直观看到是否有隐藏字符
    print("扫描到的条码: '$barcode'");
    
  3. 容错扩展(可选)
    如果条码存在前导零的情况,可以统一处理格式后再匹配:

    final cleanedBarcode = barcode.trim().replaceFirst(RegExp(r'^0+'), '');
    final item = staticItems[cleanedBarcode] ?? staticItems[barcode.trim()];
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:15:40