DartCodegenTooling

Indexing Assets in a Dart Class Just Like R.java

2020-09-22 · 6 min read · by Ishaq Hassan

Auto-generate typed asset references with codegen, inspired by Android's R.java. Drop string-based asset paths forever.

Read on

Read on Medium โ†’

Key takeaways

Frequently asked questions

Do I need build_runner or just a script?

A plain Dart script that scans /assets and writes lib/generated/assets.dart is enough. build_runner is overkill unless you already use it for other codegen.

What if my designer renames an asset?

Re-run the generator. Any usage referencing the old name fails to compile, which is the entire point. You catch the rename at build time, not at runtime in production.

Can this work with --tree-shake-icons?

Yes. The generator emits string constants, not Widget instances. Tree-shaking still applies normally to anything you build with those strings.

Is there a published package?

Yes: assets_indexer on pub.dev. Or copy the generator into your own project; it is roughly 80 lines of Dart.