执行以下命令时出现NoSuchMethodError: invalid member on null: 'user'
错误。我以为我缺少构造函数或setter或初始化错误。
class Mac{
MacUser user;
Mac({
this.user
});
}
class MacUser{
String username;
String password;
MacUser({
this.username,
this.password,
});
}
void main(){
Mac mac;
mac.user.username = "root"; // NoSuchMethodError: invalid member on null: 'user'
mac.user.password = "root";
}
答案 0 :(得分:1)
您正在尝试将属性设置为空对象。您需要先定义一些值才能更改:
示例:
Mac mac = new Mac(user: MacUser(username: "username", password: "password")); // initialize some value first
mac.user.username = "root";
mac.user.password = "root";
答案 1 :(得分:0)
Mac mac = new Mac(user: new MacUser()); // this line will Create a Null Object as you may or may not have both values at this time later on you can edit those value by below code
mac.user.username = "root";
mac.user.password = "root";