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

Implement pattern matching #4

Closed
fujidaiti opened this issue Jul 13, 2023 · 0 comments · Fixed by #7
Closed

Implement pattern matching #4

fujidaiti opened this issue Jul 13, 2023 · 0 comments · Fixed by #7
Labels
enhancement New feature or request

Comments

@fujidaiti
Copy link
Owner

fujidaiti commented Jul 13, 2023

It would be nice if we could control how the content in a file is converted to a dart object by giving a variable annotated with @EmbedLiteral a concrete type like Map<String, int>.

For example, suppose there is a JSON file such as:

// data.json
{ "apple": 0, "banana": 1, "orange": 2 }

Then we should be able to control how the above JSON object is converted into a Dart object by declaring the variable with a type:

// main.dart

@EmbedLiteral("./data.json")
// This variable should be a Map literal
const Map<String, int> dataAsMap = _$dataAsMap;

EmbedLiteral("./data.json")
// This variable should be a record literal
const ({ int apple, int banana, int orange }) dataAsRecord = _$dataAsRecord;

The generated code will look like this:

// main.g.dart
const _$dataAsMap = { "apple": 0, "banana": 1, "orange": 2 };
const _$dataAsRecord = ( apple: 0, banana: 1, orange: 2 );

Even better, this pattern matching allows you to partially extract data from the content file by specifying a desired structure of the record literal to be generated.

// another_main.dart

@EmbedLiteral("./data.json")
// takes only the `apple` and `banana` data from `data.json
const ({ int apple, int banana }) partialData = _$partialData;

This will generate the source:

// another_main.g.dart
const _$partialData = ( apple: 0, banana: 1 );

These features are useful to ensure that the generated objects always have the same structure, or in cases where the content is huge but only a portion of it is of interest.

@fujidaiti fujidaiti added the enhancement New feature or request label Jul 13, 2023
@fujidaiti fujidaiti linked a pull request Jul 18, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant