Fault 1: Dart does not support Chinese keys

enum CostType {
  /// According to the square
  BySquare,
  /// According to the length of the
  ByLength,
  /// According to the weight
  ByWeight,
  /// According to the number of
  ByNum,
}

extension CostTypeExtension on CostType {
  static const labels = ["Square"."By length"."By weight"."By quantity"];

  /// The value displayed in the foreground
  String get label => labels[this.index];
  /// Parse the value from the background
  static FeeType parse(int i) {
    return FeeType.values[i];
  }
  /// Parse the Chinese Label value from the background
  static FeeType parseLabel(String label) {
    int index = labels.indexOf(label);
    if (index == - 1) throw FormatException('Label is not acceptable ');
    returnparse(index); }}Copy the code

By extending the enumeration, it can save Chinese

When used

  • Parse the value passed from the backgroundcostType: json["costType"] ! = null? CostTypeExtension.parse(json["costType"]): null
  • Flutter display, such as select as items, can be used directlyCostTypeExtension.labels
  • Gets the Chinese meaning of the current enumeration type,Costtype.bysquare.label == "square"

Problem 2: Enumeration types in the Dart language are not free to define where an enumeration starts

Let’s say I want the enumeration to start at -1 to represent the canceled state, which DART doesn’t support, or I don’t want to start at 0 and just start at 1

import 'package:flutter/material.dart';
enum Status {
  /// sent
  ToBeSent,
  /// Has been sent
  HasBeenSent,
  /// Have received
  Received,
  /// Have to reply
  Replied,
  /// Has been cancelled
  Canceled,
}

extension StatusExtension on Status {
  static const List<int> values = [0.1.2.3.- 1];
  static const List<String> labels = [
    "To be sent"."Sent".received."Replied"."Cancelled"
  ];
  static const List<Color> colors = [
    Color(0xffb4b4b4),
    Color(0xfff79d8c),
    Color(0xff00b9f1),
    Color(0xff2699f6),
    Color(0xff75d239)];/// The value that the background really wants
  int get value => values[this.index];
  /// Show the words
  String get label => labels[this.index];
  /// The color
  Color get color => colors[this.index];
  /// Parse the value from the background
  static Status parse(int i) {
    if (i == - 1) return Status.Canceled;
    returnStatus.values[i]; }}Copy the code

In this way, it has three types of attributes (not including color), namely the original index, and the extended value and label to represent the actual and background constraint values and display values

The Status enumeration type is converted to the real value in the background when it is passed to the background. And values from background requests are resolved into the enumerated types used in FLUTTER

conclusion

Provide an idea, have other ideas please leave a message. In addition, you see the officer passed by, praise do not miss ~~ 😀