Flutter 枚舉值enum和int互相轉(zhuǎn)化總結(jié)
一、需求來源
工作中偶爾會用到枚舉值和 int 的互相轉(zhuǎn)化,今天總結(jié)一下;
二、搞清楚 Flutter 枚舉屬性和方法

三、實(shí)現(xiàn)需求(以 PageView 滾動方式為例)
枚舉值轉(zhuǎn) int:在當(dāng)前索引值后加 .index 即可(默認(rèn)從 0 開始);
int 轉(zhuǎn)枚舉值:需要擴(kuò)展枚舉方法實(shí)現(xiàn),實(shí)現(xiàn)如下;
定義枚舉 PageViewScrollType
/// PageView 滾動方式
enum PageViewScrollType {
/// 整屏滑動
full,
/// 拖拽滑動
drag,
/// 禁用滑動
none,
}
extension PageViewScrollType_IntExt on int{
/// int 轉(zhuǎn)枚舉
PageViewScrollType? toPageViewScrollType([bool isClamp = true]){
final allCases = PageViewScrollType.values;
if (!isClamp) {
if (this < 0 || this > allCases.length - 1) {
return null;
}
return allCases[this];
}
final index = this.clamp(0, allCases.length - 1);
return allCases[index];
}
/// int 轉(zhuǎn)枚舉
PageViewScrollType get pageViewScrollType{
final allCases = PageViewScrollType.values;
// final index = this.clamp(0, allCases.length - 1);
// return allCases[index];
return this.toPageViewScrollType(true) ?? allCases.first;
}
}
最后
如此就實(shí)現(xiàn)了 枚舉值和 int的互相轉(zhuǎn)化,打印如下:
print("枚舉值索引: ${PageViewScrollType.full.index}");
print("枚舉值字符串: ${PageViewScrollType.drag.toString()}");
print("枚舉集合: ${PageViewScrollType.values}");
print("int 轉(zhuǎn)枚舉: ${0.toPageViewScrollType()}");
//枚舉值索引: 0
//枚舉值字符串: PageViewScrollType.drag
//枚舉集合: [ PageViewScrollType.full, PageViewScrollType.drag, PageViewScrollType.none ]
//int 轉(zhuǎn)枚舉: PageViewScrollType.full
以上就是Flutter 枚舉值enum和int互相轉(zhuǎn)化總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Flutter枚舉值enum int互相轉(zhuǎn)化的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一款A(yù)ndroid APK的結(jié)構(gòu)構(gòu)成解析
本篇文章介紹了我在學(xué)習(xí)過程中對于Android 程序的理解總結(jié),刨析了apk的組成與產(chǎn)生過程,通讀本篇對大家的學(xué)習(xí)或工作具有一定的價值,需要的朋友可以參考下2021-10-10
詳解Android使用CoordinatorLayout+AppBarLayout+CollapsingToolbarL
這篇文章主要為大家詳細(xì)介紹了Android使用CoordinatorLayout+AppBarLayout+CollapsingToolbarLayou實(shí)現(xiàn)手指滑動效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
Android調(diào)用系統(tǒng)自帶瀏覽器打開網(wǎng)頁的實(shí)現(xiàn)方法
在Android中可以調(diào)用自帶的瀏覽器,或者指定一個瀏覽器來打開一個鏈接。只需要傳入一個uri,可以是鏈接地址。接下來通過本文給大家分享android 自帶瀏覽器打開網(wǎng)頁的實(shí)現(xiàn)方法,需要的朋友參考下吧2017-09-09
Android中利用SurfaceView制作抽獎轉(zhuǎn)盤的全流程攻略
這篇文章主要介紹了Android中利用SurfaceView制作抽獎轉(zhuǎn)盤的全流程,從圖案的繪制到轉(zhuǎn)盤的控制再到布局,真的非常全面,需要的朋友可以參考下2016-04-04
Android?Framework原理Binder驅(qū)動源碼解析
這篇文章主要為大家介紹了Android?Framework原理Binder驅(qū)動源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
android使用Jsoup 抓取頁面的數(shù)據(jù)
本篇文章主要介紹了android使用Jsoup 抓取頁面的數(shù)據(jù),jsoup 是一款Java的HTML解析器,有需要的朋友可以了解一下。2016-11-11

