Flutter BarCode 使用 QR 码扫描仪检查数据是否包含字母/单词

Flutter BarCode to check if data contains Letters/Word with QR Code Scanner

提问人:Chuah Sze Wei 提问时间:10/19/2023 更新时间:10/19/2023 访问量:46

问:

嗨,我一直在尝试读取QR码,然后在扫描数据包含特定关键字时导航到页面。目前,我确实打印了数据并且它显示正确,但是当我想通过它来检查 startsWith 时,它会显示以下错误。我也尝试使用包含(相同的错误),我确实在应用之前检查了值是否为 null,并且我还添加了 ?在初始化条形码之前。该代码是从包qr_code_scanner示例编辑的。我觉得相关的代码只在这里。我不确定我现在缺少什么来消除此错误。请帮忙。

void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((Barcode? scanData) {
      setState(() {
        Barcode? result;
        result = scanData;
        if (result != null){
          if(result!.code.startsWith("anything")){
            \\Navigate here
          }
        }
        
      });
    });
  }

我收到如下所示的错误result!.code.startsWith("anything")

The method 'startsWith' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!').
null 调用 flutter-qrcode

评论


答:

0赞 Keval 10/19/2023 #1

您应该尝试将方法中的 if 条件更新为以下内容:

if (result != null) {
    if (result.code?.startsWith("anything") ?? false) {
      // TODO: Add the navigation code
    }
  }
0赞 Munsif Ali 10/19/2023 #2

像这样更改条件

if(result !=null && result.code!=null){
   if (result!.code!.startsWith("anything")) {
       // do you navigation here
    }
}

评论

0赞 Chuah Sze Wei 10/19/2023
这对我有用,似乎这也可以通过 Visual Studio Code 自动修复进行调试,我只是在使用您的解决方案后才注意到它。谢谢
0赞 Munsif Ali 10/19/2023
是的,您可以通过键盘快捷键在 VS Code 中获得快速解决方案ctrl+.