Flutter枚举
Flutter枚举
Enum Extension
在Dart
2.7版本,Dart
新增了扩展函数,使枚举相关的代码定义、调用更加简洁
通过扩展枚举定义方法
定义一个元素枚举
enum Element { hydrogon, carbon, oxide }
定义一个枚举扩展,通过switch case
获取每个元素的相对原子质量和中文描述
extension ElementExtension on Element {
int get number {
switch (this) {
case Element.hydrogon:
return 1;
case Element.carbon:
return 6;
case Element.oxide:
return 8;
}
}
String get description {
switch (this) {
case Element.hydrogon:
return '氢气';
case Element.carbon:
return '碳';
case Element.oxide:
return '氧气';
}
}
定义一个静态方法来通过相对原子质量获取
static Element fromNumber(int number) {
switch (number) {
case 1:
return Element.hydrogon;
case 6:
return Element.carbon;
case 8:
return Element.oxide;
default:
return Element.oxide;
}
}
增强枚举类型
在Flutter
3.0 发布之后,直接在枚举构造方法内部定义相关属性,枚举值声明处进行声明即可
在pubspec.yaml文件中须将sdk版本设置为大于2.17.0
定义一个动物枚举,并定义成员变量name
和weight
和构造函数
enum Animal {
const Animal({required this.name, required this.weight});
final String name;
final int weight;
}
创建枚举类型dog
和cat
dog(name: 'dog', weight: 20),
cat(name: 'cat', weight: 6);
通过name
和weight
获取枚举类型
factory Animal.fromName(String name) {
return Animal.values.firstWhere((element) => element.name == name);
}
factory Animal.fromWeight(int weight) {
return Animal.values.firstWhere((element) => element.weight == weight);
}
这里直接构造了两个工厂函数,接收name
或者weight
参数,通过遍历Animal
的values
,筛选出和参数相同的枚举类型并返回
也可以通过静态方法的方式
static Animal fromNameStatic(String name) {
return Animal.values.firstWhere((element) => element.name == name);
}
static Animal fromWeightStatic(int weight) {
return Animal.values.firstWhere((element) => element.weight == weight);
}
创建枚举并访问成员变量
const dog = Animal.dog;
log(dog.name);
log(dog.weight.toString());
定义toJson
方法将枚举类型的所有信息打印
Map<String, dynamic> toJson() {
return {'name': name, 'weight': weight};
}
完整代码
enum Animal {
dog(name: 'dog', weight: 20),
cat(name: 'cat', weight: 6);
const Animal({required this.name, required this.weight});
factory Animal.fromName(String name) {
return Animal.values.firstWhere((element) => element.name == name);
}
factory Animal.fromWeight(int weight) {
return Animal.values.firstWhere((element) => element.weight == weight);
}
static Animal fromNameStatic(String name) {
return Animal.values.firstWhere((element) => element.name == name);
}
static Animal fromWeightStatic(int weight) {
return Animal.values.firstWhere((element) => element.weight == weight);
}
Map<String, dynamic> toJson() {
return {'name': name, 'weight': weight};
}
final String name;
final int weight;
}
Dart2.7之前
在Dart
2.7 的扩展函数发布之前,一般是新建一个顶级函数/工具类内部函数,使用swtich case
来返回枚举值对应的关联数据
String getName(Animal animal) {
switch (animal) {
case Animal.dog:
return 'dog';
case Animal.cat:
return 'cat';
}
}
反之亦然
Animal getType(String name) {
switch (name) {
case 'dog':
return Animal.dog;
case 'cat':
return Animal.cat;
default:
return Animal.dog;
}
}