我猜不同的笑點(diǎn),代表不同的智力水平。
前言
今年四月初寫Flutter的時(shí)候,覺得里面的枚舉著實(shí)有點(diǎn)難受,先不說Swift了,和oc相比都差太多,最起碼oc能賦值。不知怎的剛才突發(fā)奇想,仔細(xì)研究一下Flutter枚舉,沒想到還有真有好用的寫法。
正文
如果枚舉值對應(yīng)的值是從0開始遞增的,那就太好了,直接下面寫就行了。
enum RoomType {
/// 游戲
game,
/// 歌廳
song,
/// 直播
live,
}
使用的時(shí)候直接用對應(yīng)的index就ok,例:
int roomType = RoomType.song.index; /// 值為1
但是,如果枚舉的值不是從0開始的怎么辦?如果枚舉值對應(yīng)的是字符串呢?沒關(guān)系,寫擴(kuò)展。
-
枚舉擴(kuò)展
extension RoomTypeValue on RoomType {
String get value {
String _value = '';
switch (this) {
case RoomType.game:
_value = '1';
break;
case RoomType.song:
_value = '3';
break;
case RoomType.live:
_value = '5';
break;
default:
}
return _value;
}
}
使用:
String roomType = RoomType.song.value; /// 值為 '3'
可以看出,如果想對應(yīng)其他的整型的值,就再寫一個(gè)get方法,然后再用switch case即可,對于前期學(xué)習(xí)的我就湊合著用了,但內(nèi)心還是覺得這種寫法有點(diǎn)丑陋。
萬幸的是,隨著 2022 年 5 月在 Google I/O上發(fā)布Flutter 3.0,我們不必再依賴這些令人長長的代碼了。來看一下用最新寫法替代上面的擴(kuò)展吧。
-
枚舉新寫法
enum RoomType {
/// 游戲
game('1'),
/// 歌廳
song('3'),
/// 直播
live('5');
final String value;
const RoomType(this.value);
}
使用:
String roomType = RoomType.song.value; /// 值為 '3'
簡潔!好用!
有的小伙伴會(huì)說,如果還對應(yīng)整型值呢?沒關(guān)系,往下看:
enum RoomType {
/// 游戲
game('1', 1),
/// 歌廳
song('3', 3),
/// 直播
live('5', 5);
final String value;
final int number;
const RoomType(this.value, this.number);
}
使用:
String roomType = RoomType.song.value; /// 值為 '3'
int roomType = RoomType.song.number; /// 值為 3
由此可見,想映射啥就映射啥,想映射幾個(gè)就映射幾個(gè),有種鳥槍換炮的感覺,恐怖如斯。
后記
我查閱的資料的說的是3.0以后可以使用,我用的Dart版本是3.0.5,但是實(shí)測只要是2.17.0以后就行了,具體為啥沒有咋研究。