Flutter 枚举值enum和int互相转化总结
SoaringHeart 人气:0一、需求来源
工作中偶尔会用到枚举值和 int 的互相转化,今天总结一下;
二、搞清楚 Flutter 枚举属性和方法
三、实现需求(以 PageView 滚动方式为例)
枚举值转 int:在当前索引值后加 .index 即可(默认从 0 开始);
int 转枚举值:需要扩展枚举方法实现,实现如下;
定义枚举 PageViewScrollType
/// PageView 滚动方式 enum PageViewScrollType { /// 整屏滑动 full, /// 拖拽滑动 drag, /// 禁用滑动 none, } extension PageViewScrollType_IntExt on int{ /// int 转枚举 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 转枚举 PageViewScrollType get pageViewScrollType{ final allCases = PageViewScrollType.values; // final index = this.clamp(0, allCases.length - 1); // return allCases[index]; return this.toPageViewScrollType(true) ?? allCases.first; } }
最后
如此就实现了 枚举值和 int的互相转化,打印如下:
print("枚举值索引: ${PageViewScrollType.full.index}"); print("枚举值字符串: ${PageViewScrollType.drag.toString()}"); print("枚举集合: ${PageViewScrollType.values}"); print("int 转枚举: ${0.toPageViewScrollType()}");
//枚举值索引: 0
//枚举值字符串: PageViewScrollType.drag
//枚举集合: [ PageViewScrollType.full, PageViewScrollType.drag, PageViewScrollType.none ]
//int 转枚举: PageViewScrollType.full
加载全部内容