Generate Static Assets References for Flutter

Muhammad Iqbal
2 min readApr 18, 2019

--

NOTE: As per 12 Oct 2020, this article is quite old. There are already some plugins to resolve this problem. You can search with the keyword “asset generator” at pub.dev. But if you are reluctant to add more dependencies to your project, please continue reading.

Working with assets in early development never been easy, especially images and icons which kept being changed and improved all the time. One day we adding some icons, next month we might be asked to remove some and replace the rest. In Flutter, we refer to assets by their paths as String which (in my opinion) might lead to typos and making mess everywhere on my code.

https://hips.hearstapps.com/digitalspyuk.cdnds.net/15/21/ustv-rick-morty-simpsons-couch-gag.jpg

Personally, I prefer to create static references in one file. Whenever I need to refer assets, I just write references to that file. This approach has the following benefits:

  • It’s easier to track where an assets being referenced in code.
  • It’s also easier to track unused assets in code, so I can remove it and reduce app size
  • Any typos will be concentrated in one place. No need make fix on every files referencing that mistake.

but by doing this...another problem arises:

https://tenor.com/view/djkhaled-another-one-one-gif-5057861

I’m too lazy to migrate those assets paths into references! There are already tens of them. What if there are hundreds? This might bore me to death if I had to do those manually. Luckily, I have powerful companion at my side: Bash to the rescue!

First of all, my file naming convention is using snake_case or kebab-case, while dart prefers camelCase. I need regex to convert filename info camelCase.

regex='s/[-_]([a-z0-9])/\U\1/gi'

Then all I need is to list all files under my images folder, get their filename, turn it into camelCase , write it as variable name and assign its path as variable value.

for f in `find ./assets/images -maxdepth 1 -type f`; do   filename=`echo $f | cut -d'/' -f4 | cut -d'.' -f1`
varname=`echo $filename | sed -E $regex`
entry="static const String $varname = '${f:2}';"
echo " $entry" >> tmp;
done;

Here’s the complete example:

Just run this script inside the root of your flutter project and voila! assets.dart will be generated under lib/assets

I do prefer running this script rather than add references manually, even though I only need to add one new asset.

You can improve this script to loop all folders within assets , e.g. if you have images, icons, or animations in separate folders.

Hope this helps 😄

--

--