如何从json结构生成Dart代码 [英] How to generate Dart code from json structure

查看:144
本文介绍了如何从json结构生成Dart代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code_build https:// pub .dartlang.org / packages / code_builde )包提供了一种为该类生成类以及构造函数,字段和方法的解决方案。



我的最终目标是基于给定的json结构生成Flutter( https://flutter.io )小部件,但我不知道如何可以使用 code_build 或其他软件包来完成此操作。



因此,我们将不胜感激!

解决方案

编写输出Dart代码的东西的一般方法是将功能包装在 Builder 并使用 build_runner



在较高级别上,您将编写一个 Builder : / p>


  • buildExtensions {。json:[ .dart]}

  • 读取 buildStep.inputId 资产并解析json。

  • 使用 code_builder 构建一个字符串,然后将其写入输出资产。



然后您 build.yaml 中配置构建器。然后将其手动应用于您的软件包,或者如果您希望将其作为实用程序发布,它可以应用于依赖项。



您的软件包将具有 dev_dependency build_runner 上,然后可以使用 flutter包执行构建,运行build_runner build



https://github.com/dart-lang/build/tree/master/docs



您可以看到一个包示例这样做的方式相似-从yaml文件开始,并使用 code_builder https://github.com/natebosch/message_builder


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!

解决方案

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

这篇关于如何从json结构生成Dart代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆