一、需求来源
工作中偶尔会用到枚举值和 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;
}
}
EnumExt - 枚举通用扩展
//
// EnumExt.dart
// flutter_templet_project
//
// Created by shang on 2024/7/10 09:47.
// Copyright © 2024/7/10 shang. All rights reserved.
//
import 'package:flutter/cupertino.dart';
/// 可空 name 匹配
extension EnumExt<T extends Enum> on Iterable<T> {
/// Finds the enum value in this list with name [name].
T? byNullableName(String? name) {
if (name == null) {
return null;
}
try {
return byName(name);
} catch (e) {
debugPrint("❌ $e");
}
return null;
}
/// Finds the enum value in this list with test.
T? by(bool Function(T e) test) {
for (final e in this) {
if (test(e)) {
return e;
}
}
return null;
}
}
extension EnumStringExt<T extends Enum> on String? {
/// 字符串转枚举
/// values - 枚举数组
T? enumOf(Iterable<T> values) {
return values.byNullableName(this);
}
}
最后
如此就实现了 枚举值和 int的互相转化,打印如下:
print("枚举值索引: ${PageViewScrollType.full.index}");
print("枚举集合: ${PageViewScrollType.values}");
print("int 转枚举: ${0.toPageViewScrollType()}");
String? name = ...;
/// 通过字符串枚举值 name 获取 PageViewScrollType
print("枚举值字符串: ${PageViewScrollType.values.byNullableName(name)}");
print("枚举值字符串: ${name?.enumOf(ActivityTypeNew.values)}");
/// 通过 int 获取 PageViewScrollType
print("枚举值字符串: ${PageViewScrollType.values.by((e) => e.index == 2);}");
//枚举值索引: 0
//枚举值字符串: PageViewScrollType.drag
//枚举集合: [ PageViewScrollType.full, PageViewScrollType.drag, PageViewScrollType.none ]
//int 转枚举: PageViewScrollType.full