扫码后如何在两个Text组件中分别显示不同的条码数据?
解决扫码结果拆分显示问题
核心思路
将扫码返回的含双值的字符串拆分为独立变量,再分别绑定到两个Text组件即可实现分别显示。以下是具体修改步骤:
1. 替换单变量为双独立变量
把原来的单个scanResult变量,替换为两个用于存储拆分后结果的变量:
String? scanValue1; String? scanValue2;
2. 修改扫码方法,拆分返回结果
扫码成功后对返回字符串进行拆分(假设结果以逗号分隔,如"12345,abcde";若为其他分隔符,替换成对应符号即可),同时处理异常情况:
Future scanBarcode() async { String scanResult; try { scanResult = await FlutterBarcodeScanner.scanBarcode("#ff6666", "Cancel", true, ScanMode.BARCODE); // 排除用户取消扫码的情况 if (scanResult != "-1") { // 拆分结果,根据实际格式调整分隔符 List<String> resultParts = scanResult.split(','); setState(() { scanValue1 = resultParts.length >= 1 ? resultParts[0] : ""; scanValue2 = resultParts.length >= 2 ? resultParts[1] : ""; }); } } on PlatformException { setState(() { scanValue1 = '获取平台版本失败'; scanValue2 = ''; }); } }
3. 更新Text组件绑定对应变量
让两个Text组件分别绑定scanValue1和scanValue2:
Text( scanValue1 ?? '', textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.bold, ), ), Text( scanValue2 ?? '', textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.bold, ), ),
注意事项
- 若扫码结果的分隔符不是逗号,只需修改
split(',')中的符号为实际分隔符(如空格、竖线|等)。 - 增加了长度判断,避免因扫码结果格式异常导致索引越界报错。
内容的提问来源于stack exchange,提问作者sarah
相关产品推荐
相关产品推荐

