从Dart 2.17开始,我们可以用成员声明枚举。🚀
这里有一个例子。
enum AuthException {
invalidEmail('Invalid email'),
emailAlreadyInUse('Email already in use'),
weakPassword('Password is too weak'),
wrongPassword('Wrong password');
const AuthException(this.message);
final String message;
}
const exception = AuthException.wrongPassword;
print(exception.message); // Wrong password
你还能用它做什么?
- 定义多个属性
- 为构造函数添加命名或位置参数(只要它是一个构造函数)。
- 定义自定义方法和获取器
下面是另一个例子。
enum StatusCode {
badRequest(401, 'Bad request'),
unauthorized(401, 'Unauthorized'),
forbidden(403, 'Forbidden'),
notFound(404, 'Not found'),
internalServerError(500, 'Internal server error'),
notImplemented(501, 'Not implemented');
const StatusCode(this.code, this.description);
final int code;
final String description;
@override
String toString() => 'StatusCode($code, $description)';
}
这意味着我们不再需要自定义扩展来为枚举 "添加 "功能,这使得我们的代码更加清晰和简洁。
关于Dart 2.17引入的所有语言功能的更多信息,请阅读完整的公告。
编码愉快!