👋
DartのEnumってString以外は使えるのか?
Tips💡
引数付きのEnumが追加されるまでは、Stringしか使えなかったようだ...
こんな感じ
enum Hoge {
tato,
jiro,
hanako,
}
引数付きのEnumが追加されてからは、どうやらどんなデータ型でもつけることできるようになったかもしれない???
bool:
typedef IL = bool;
enum AuthorizationStatus {
login(true),
logout(false);
const AuthorizationStatus(this.value);
final IL value;
}
int:
typedef MN = int;
enum Numbers {
ONE(1),
TWO(2),
THREE(3);
const Numbers(this.membersNumber);
final MN membersNumber;
}
status code int:
typedef SC = int;
enum StatusCodes {
// success
SUCCESS(200),
// created
CREATED(201),
// accepted
ACCEPTED(202),
// no content
NO_CONTENT(204),
// redirect
MOVED_PERMANENTLY(301),
// client errors
BAD_REQUEST(400),
// unauthorized
UNAUTHORIZED(401),
// forbidden
FORBIDDEN(403),
// not found
NOT_FOUND(404),
// server errors
INTERNAL_SERVER_ERROR(500);
const StatusCodes(this.statusCode);
final SC statusCode;
}
Color:
typedef MC = MaterialColor;
enum ColorT {
GREEN(Colors.green),
BLUE(Colors.blue),
RED(Colors.red);
const ColorT(this.materialColor);
final MC materialColor;
}
まとめ
今回は、列挙型であるEnumの引数を使えるタイプで、文字以外が使えることを知ることができました。他にも何か使い道あるかもしれないですね。もしかしたら、sealed classの方が使いやすかったりして...
Discussion