作者:笨蚂蚁88 | 来源:互联网 | 2022-12-04 10:50
有没有办法设置构造函数的可选参数?我的意思是:
User.fromData(this._name,
this._email,
this._token,
this._refreshToken,
this._createdAt,
this._expiresAt,
this._isValid,
{this.id});
它表明
命名选项参数不能以下划线开头。
但是我需要将此字段作为私有字段,因此,我现在迷路了。
1> Alexandre Ar..:
您需要使用一个简单的参数,并在初始化列表中初始化您的私有字段。
class User {
final String _id;
final String _name;
User.fromData(this._name, {String id})
: _id = id;
}
2> Suragch..:
对于将来的观众来说,这是一个更普遍的答案。
位置可选参数
将可选参数用[ ]
方括号括起来。
class User {
String name;
int age;
String home;
User(this.name, this.age, [this.home = 'Earth']);
}
User user1 = User('Bob', 34);
User user2 = User('Bob', 34, 'Mars');
命名可选参数
用{ }
花括号将可选参数包裹起来。
class User {
String name;
int age;
String home;
User(this.name, this.age, {this.home = 'Earth'});
}
User user1 = User('Bob', 34);
User user2 = User('Bob', 34, home: 'Mars');
注意
如果需要专用字段,则可以使用[]
方括号:
class User {
int _id;
User([this._id]);
}
User user = User(3);
或按照接受的答案说做,并使用初始化列表:
class User {
int _id;
User({int id})
: _id = id;
}
User user = User(id: 3);