skip to Main Content

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 ('!').

2

Answers


  1. you should try updating if condition inside your method to the following:

    if (result != null) {
        if (result.code?.startsWith("anything") ?? false) {
          // TODO: Add the navigation code
        }
      }
    
    Login or Signup to reply.
  2. change the condition like this

    if(result !=null && result.code!=null){
       if (result!.code!.startsWith("anything")) {
           // do you navigation here
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search