Search code examples
dartnosuchmethoderror

? operator to avoid NoSuchMethodError in dart


I saw a video of someone try to avoid NoSuchMethodError by using ? operator . here's the code:

/*1*/ void main () {

/*2*/ var v = vu() ;
/*3*/ var f = v.casting()  ;
/*4*/ f.tbu ;

/*5*/}

show error on line 4

Unhandled exception: NoSuchMethodError: The getter 'tbu' was called on null. Receiver: null Tried calling: tbu

but he used the ? operator :

/*1*/ void main () {

/*2*/ var v = vu() ;
/*3*/ var f = v.casting()  ;
/*4*/ f?.tbu ;

/*5*/}

run without problem .

My question is what is the ? operator ??


Solution

  • The question mark placed before the dot allows conditional property access, which guards against trying to access a property or method of an object that might be null:

    myObject?.someProperty
    

    is equivalent to the following:

    (myObject != null) ? myObject.someProperty : null
    

    This is similar to optional chaining in JavaScript.