📜 ⬆️ ⬇️

Code Generation in Dart. Part 1. Basics

It is known that it is very good for a programmer to be lazy , because doing more with less is the key to progress . Nobody likes to do the same thing over and over again. It is tiring, boring, and not at all creative. Repeating the same action, we often make mistakes, but, fortunately, there are those who are really good and effective in performing the same type of tasks. And these are COMPUTERS !


https://yougottobekidding.wordpress.com/2012/02/18/geeks-and-repetitive-tasks/


Today, code generation is the ability to do work in the shortest amount of time . The basic idea is simple: to find patterns in the same type and tedious parts of the code that you have to write again and again, create a tool for generating, run it and see how the magic happens!


In the Android world of development, such tools are well known to every developer. This and Retrofit, and Dagger, and Room. What about dart? And no less important question: what do we need to create our own tools for code generation?


Dart and code generation: available tools


To create a code generation tool, we need the following two packages:



source_gen


This package provides a convenient API for code generation. This is an abstraction over some low-level Dart packages, such as analyzer and build . Although the use of this package is optional, it can relieve you of many difficulties.


source_gen provides two abstract generator classes that follow the Visitor pattern:



You also need to configure the Builder , which will wrap the generator. There are three options:



build_runner


This tool allows you to start the generator at the design stage. It can be called from the constant line:


 pub run build_runner <command> 

At the place of <command> can be:



In order for source_gen work, you also need to create the buil.yaml file, which specifies the details of the code generator configuration.


Using Code Generation in Dart


Code generation is used in many well-known Dart libraries:



Further...


The second part will show how to use annotations and code generation to track all the TODO in the application.


')

Source: https://habr.com/ru/post/445824/


All Articles