问题
The code_build
(https://pub.dartlang.org/packages/code_builde) package provides a solution to generate classes and constructors, field and methods for that class.
My ultimate goal is to generate Flutter (https://flutter.io) Widgets based on the json structure given, but I don't know how to do this with the code_build
or another package.
So help would be appreciated!
回答1:
The general way to write something which outputs Dart code is to wrap up the functionality in a Builder and to perform the code generation with build_runner
At a high level you'd write a Builder
that:
- Has
buildExtensions
of{".json": [".dart"]}
. - Reads in the
buildStep.inputId
asset and parses the json. - Uses
code_builder
to build up a String and then write it to the output asset.
Then you'd configure the builder in build.yaml. And either apply it manually to your package, or if you'd like to publish it as a utility it can apply to dependencies.
Your package would have a dev_dependency
on build_runner
and then you can execute builds with flutter packages run build_runner build
.
There are more docs at https://github.com/dart-lang/build/tree/master/docs
You can see an example of a package which does something similar - starts with yaml files and outputs Dart files using code_builder
at https://github.com/natebosch/message_builder
回答2:
There is now an online tool which will generate the Dart classes from a JSON payload if you're only looking to structure your model classes. It won't do it dynamically at runtime, but it's super helpful when you're first building your program.
https://javiercbk.github.io/json_to_dart/
来源:https://stackoverflow.com/questions/53270688/how-to-generate-dart-code-from-json-structure