工作中偶尔会用到枚举值和 int 的互相转化,今天总结一下;
枚举值转 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
以上就是Flutter 枚举值enum和int互相转化总结的详细内容,更多关于Flutter枚举值enum int互相转化的资料请关注脚本之家其它相关文章!
编程 | 2023-02-24 21:36
编程 | 2023-02-21 12:51
编程 | 2023-02-21 12:47
编程 | 2023-02-21 00:15
编程 | 2023-02-21 00:08
编程 | 2023-02-20 21:46
编程 | 2023-02-20 21:42
编程 | 2023-02-20 21:36
编程 | 2023-02-20 21:32
编程 | 2023-02-20 18:12
网友评论