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

Type casting in model.fromJson map #417

Open
Tracked by #431
kidusdev opened this issue Aug 25, 2024 · 1 comment
Open
Tracked by #431

Type casting in model.fromJson map #417

kidusdev opened this issue Aug 25, 2024 · 1 comment

Comments

@kidusdev
Copy link

kidusdev commented Aug 25, 2024

Sale.fromJson(s)

factory Sale.fromJson(Map json) => Sale(
        id: json['id'],
        quantity: json['quantity'],
        // eg. quantity: double.tryParse("${json['quantity']}") 
       // this way it can convert String, int, num to double so you don't have to worry about the api data type 
        unitPrice: json['unit_price'],
        createdAt: switch (json['created_at']) {
          DateTime value => value,
          String value => DateTime.parse(value),
          _ => json['created_at']
        },
      );

in this example the Map json data is coming from an api but the quantity is either double or int but the model's quantity field only accepts double. can we parse and cast it to double or are there any other available methods to deal with. i could cast every field but it would be if we have this feature inside the model instead of all over my project

@medz
Copy link
Owner

medz commented Aug 26, 2024

I am waiting for the official release of macros. Previously, FromJson and ToJson relied on code generate.

@medz medz mentioned this issue Sep 26, 2024
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants