如果对象不为 null 则调用方法(对 void 方法使用 null 安全)

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

有没有办法做到 void? callMe()? 因为没有诸如 void? 之类的类型,因此调用此方法会导致上述错误。


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

}

您应该 return 来自 UserString(或者 String? 如果需要,但在这种情况下没有必要) =]方法:

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

    print(user?.callMe());
}

class User {
    String name;

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

因为print方法接受一个Object作为它的参数,而void不是一个对象,而String是一个Object