如何在Dart中初始化嵌套对象。 NoSuchMethodError:无效的null成员:“用户”

时间:2019-12-14 15:35:18

标签: flutter dart

执行以下命令时出现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";
}

2 个答案:

答案 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";