How to generate Dart code from json structure

情到浓时终转凉″ 提交于 2019-12-23 05:08:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!