[Part 1] Code generation in Dart: the basics

Jorge Coca
Oct 3, 2018 · 3 min read
Image for post
Image for post
Image for post
Image for post
https://yougottobekidding.wordpress.com/2012/02/18/geeks-and-repetitive-tasks/

Dart and code generation: tools available

In order to create tools that auto generate code, you will probably need to use these two packages:

source_gen

This package provides an friendly API to auto generate code. It is a better abstraction of some low level Dart packages, such as analyzer or build. While it is not mandatory to use, definitely it will save you a lot of headaches.

  • GeneratorForAnnotation: similar to a simple Generator, but in this case you will also give it an “annotation”, so every node annotated with the given annotation will be visited, and the rest of nodes that are not annotated will be ignored.
  • You can use PartBuilder if you still want to use a part approach, but control the extension file, such as .my_file.dart .
  • If you just want to write a standalone library that can be imported, use a LibraryBuilder .

build_runner

This tool allow us to run our generators during the development phase. It can be invoked from the command line in this fashion:

  • watch: runs a daemon that will run on file changes and rebuilds if necessary
  • serve: similar to watch, but also runs as a development server
  • test: for testing purposes

Who uses code generation in Dart?

When looking for inspiration and libraries that use code generation, you will immediately see some of the most famous packages available:

In the next article…

Now that we know the tools that we have available to auto generate code, in the next article of this series we will focus on a tiny project where we will use annotations and code generation keep track of all the TODOs in our application.



Flutter Community

Articles and Stories from the Flutter Community

Jorge Coca

Written by

Android engineer at @bmwna. Born in Madrid, living in Chicago. I have watched La La Land more times than you… and I love singing and dancing in public xD

Flutter Community

Articles and Stories from the Flutter Community

Jorge Coca

Written by

Android engineer at @bmwna. Born in Madrid, living in Chicago. I have watched La La Land more times than you… and I love singing and dancing in public xD

Flutter Community

Articles and Stories from the Flutter Community

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app