flutternullinvokeflutter-qrcode

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


Hi I have been trying to read the QR Code and then navigate to a page when scan data contains specific keyword. Currently, I did print the data and it shows correctly, but when I want pass it to check with startsWith then it show the error below. I have tried using contains as well (Same Error), I did check the value is null before applying, and I also add ? before initializing Barcode. The code is edited from the example of packages qr_code_scanner. The related code I feel like is only here. I am not sure what am I missing now to remove this error. Please help.

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
          }
        }
        
      });
    });
  }

I am getting error shown below from 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 ('!').

Solution

  • change the condition like this

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