Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Como tratar no caso de enums? #16

Open
SamuelGadiel opened this issue May 14, 2024 · 1 comment
Open

Como tratar no caso de enums? #16

SamuelGadiel opened this issue May 14, 2024 · 1 comment

Comments

@SamuelGadiel
Copy link
Contributor

SamuelGadiel commented May 14, 2024

Dado um determinado enum, por exemplo

enum PaymentType{
  money('Dinheiro'),
  billet('Boleto'),
  credit('Cartão de crédito'),
  debit('Cartão de débito'),
  none(null);

  final String? name;
  const PaymentType(this.name);
}

Eu tenho uma classe dessa forma

class Payment{
  final String id;
  final PaymentType type;
  
  const Payment({required this.id, required this.type});
  
  static Payment fromJson(Map<String, dynamic> json){
    return Payment(
      id: json['id'] ?? '',
      type: PaymentType.values.firstWhere((e) => e.name == json['type']),
    );
  }
}

Nesse caso, como eu poderia fazer a implementação usando o dson_adapter?
O enum não possui um .new
Então não tem como fazer PaymentType.new

@wellgenio
Copy link

wellgenio commented Oct 29, 2024

@SamuelGadiel , uma sugestão...

enum PaymentType {
  money('Dinheiro'),
  billet('Boleto'),
  credit('Cartão de crédito'),
  debit('Cartão de débito'),
  none(null);

  final String? label;

  const PaymentType(this.label);

  static PaymentType fromJson(String type) =>
    values.firstWhere((value) => value.name.toLowerCase() == type.toLowerCase());
}


class Person {
  final int id;
  final String name;
  final int age;
  final PaymentType type;

  Person({
    required this.id,
    required this.name,
    required this.age,
    required this.type,
  });
}

void main() {
  final dson = DSON();

  final jsonMap = {
      'id': 1,
      'name': 'Joshua Clak',
      'age': 3,
      'type': 'credit',
    };

    Person person = dson.fromJson(
      jsonMap,
      Person.new,
      resolvers: [
        (key, value) =>  //
          (key == 'type')
            ? PaymentType.fromJson(value)
            : value,
      ]
    );

    print(person.id);    /// 1
    print(person.name);  /// Joshua Clak
    print(person.age);   /// 3
    print(person.type);  /// PaymentType.credit
}

ignore o fato de uma entidade pessoa ter um tipo de pagamento hahahah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants