Calling a method if object is not null (Using null safety with void methods)

Issue

Is there a way to do such thing as void? callMe()?
Because there is no type such as void? and hence calling this method null object with result in error above.


void main(List<String> arguments) {  
     User? user;

     print(user?.callMe());  //This expression has a type of 'void' so its value can't be used.
}
 
class User {
     String name;

     User(this.name);
        
     void? callMe() { 
         print('Hello, $name');
     }      
      
     String? foo(){ // sound null safety String method
         return name;
     }

}

Solution

You should return a String (or String? if you want, but it is not necessary in this case) from the User‘s callMe method:

void main(List<String> arguments) {  
    User? user;

    print(user?.callMe());
}

class User {
    String name;

    User(this.name);
    
    String callMe() { 
        return 'Hello, $name';
    }      
}

It’s because print method accepts an Object as its parameter, and void is not an object, but String is an Object.

Answered By – Sergey

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.