有没有办法设置构造函数可选参数? 我的意思是:
User.fromData(this._name,
this._email,
this._token,
this._refreshToken,
this._createdAt,
this._expiresAt,
this._isValid,
{this.id});
表示
Named option parameters can't start with an underscore.
但是我需要这个字段作为私有(private)字段,所以,我现在迷路了。
最佳答案
对于 future 的观众来说,这是一个更普遍的答案。
用 [ ]
方括号将可选参数括起来。
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; // <-- Nullable
User(this.name, this.age, [this.home]);
}
用 { }
花括号包裹可选参数。
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');
home
的默认值是“Earth”,但和以前一样,如果您不提供默认值,则需要将 String home
更改为 String ?主页
.
如果您需要私有(private)字段,则可以使用 []
方括号:
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);
命名参数默认是可选的,但是如果你想让它们成为必需的,那么你可以使用 required
关键字:
class User {
final String name;
final int age;
final String home;
User({
required this.name,
required this.age,
this.home = 'Earth',
});
}
User user1 = User(name: 'Bob', age: 34);
User user2 = User(name: 'Bob', age: 34, home: 'Mars');
https://stackoverflow.com/questions/52449508/