Flutter Dart语言中枚举类型不支持以中文作为键名与不能自定义index不从0开始的解决办法

问题1:Dart 不支持中文做key

enum CostType {
  /// 按平方
  BySquare,
  /// 按长度
  ByLength,
  /// 按重量
  ByWeight,
  /// 按数量
  ByNum,
}

extension CostTypeExtension on CostType {
  static const labels = ["按平方", "按长度", "按重量", "按数量"];

  /// 前台展示的值
  String get label => labels[this.index];
  /// 解析从后台传来的值
  static FeeType parse(int i) {
    return FeeType.values[i];
  }
  /// 解析从后台传来的中文Label值
  static FeeType parseLabel(String label) {
    int index = labels.indexOf(label);
    if (index == -1) throw FormatException('Label不在可接受范围内');
    return parse(index);
  }
}

复制代码

通过给枚举扩展,让他可以保存中文

使用的时候

  • 解析后台传过来的值 costType: json["costType"] != null? CostTypeExtension.parse(json["costType"]): null
  • flutter展示,比如select中做items,可直接用CostTypeExtension.labels
  • 获取当前枚举类型的中文含义,CostType.BySquare.label == "按平方"

问题2:Dart语言中的枚举类型不能自由定义枚举从几开始

比如我想让枚举从-1开始代表已取消状态,dart不支持,或者我不想从0开始,直接从1开始

import 'package:flutter/material.dart';
enum Status {
  /// 待发送
  ToBeSent,
  /// 已发送
  HasBeenSent,
  /// 已接收
  Received,
  /// 已回复
  Replied,
  /// 已取消
  Canceled,
}

extension StatusExtension on Status {
  static const List<int> values = [0, 1, 2, 3, -1];
  static const List<String> labels = [
    "待发送",
    "已发送",
    "已接收",
    "已回复",
    "已取消"
  ];
  static const List<Color> colors = [
    Color(0xffb4b4b4),
    Color(0xfff79d8c),
    Color(0xff00b9f1),
    Color(0xff2699f6),
    Color(0xff75d239),
  ];
  /// 真正后台想要的值
  int get value => values[this.index];
  /// 展示文字
  String get label => labels[this.index];
  /// 展示颜色
  Color get color => colors[this.index];
  /// 解析从后台传来的值
  static Status parse(int i) {
    if (i == -1) return Status.Canceled;
    return Status.values[i];
  }
}
复制代码

这样写的话,他就拥有了3中类型的属性(不包括color),即原有的index,扩展的valuelabel用于表示实际与后台约束的值显示值

在实际使用过程中其实是用不到value的,只是要在传输给后台时候,要将Status枚举类型转换成后台真正的值;和从后台请求下来的值解析成flutter中使用的枚举类型

结束语

提供一个思路,有其他思路请留言。另外,各位看官走过路过,点赞不要错过~~ ?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享