日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Flutter?枚舉值enum和int互相轉化總結_Android

作者:SoaringHeart ? 更新時間: 2023-05-19 編程語言

一、需求來源

工作中偶爾會用到枚舉值和 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

原文鏈接:https://juejin.cn/post/7200221724045623355

欄目分類
最近更新