欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Flutter枚举值enum和int互相转化总结,

来源: 开发者 投稿于  被查看 14409 次 评论:248

Flutter枚举值enum和int互相转化总结,


目录
  • 一、需求来源
  • 二、搞清楚 Flutter 枚举属性和方法
  • 三、实现需求(以 PageView 滚动方式为例)
  • 最后

一、需求来源

工作中偶尔会用到枚举值和 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

以上就是Flutter 枚举值enum和int互相转化总结的详细内容,更多关于Flutter枚举值enum int互相转化的资料请关注3672js教程其它相关文章!

您可能感兴趣的文章:
  • Flutter配置代理抓包实现过程详解
  • Flutter SizedBox布局组件Widget使用示例详解
  • Flutter 图片开发核心技能快速掌握教程
  • flutter升级3.7.3报错Unable to find bundled Java version解决
  • Flutter WebView性能优化使h5像原生页面一样优秀

用户评论