Using asset path string directly is not safe. What happens if you change the image file name or delete the image file.

In some cases, if the number of files is too large, too many must be defined in the pubspec.yaml file.

Setup Project Flutter

  • Step 1. Download and move this file BuildAssets.java into your project.

  • Step 2. Open file pubspec.yaml

Add 2 lines, below line uses-material-design: true

# === Generated Code Start ===
# === Generated Code End ===

  • Step 3. Open terminal and run
javac BuildAssets.java
java BuildAssets

  • Step 4. Open pubspec.yaml and enjoy

Gen code

CMD Output
java BuildAssets JSON ..dart with command: % java BuildAssets JSON local.manager.reader_json.dart to gen file reader_json.dart into folder lib/local/manager/, the file is included static class ReaderJson
java BuildAssets AssetImage ..dart with command: java BuildAssets AssetImage local.manager.all_assets.dart to gen file all_assets.dart into folder lib/local/manager/, the file is included static class AllAssets

Idea

The idea from Chromium source code:

BuildConfigGenerator.groovy gen code from build.gradle to create BUILD.gnfile.

https://chromium.googlesource.com/chromium/src/+/refs/heads/master/third_party/android_deps/buildSrc/src/main/groovy/BuildConfigGenerator.groovy

Tutorial

In Flutter Project

  • Create folder assets\svgs and put all svg files into this folder. Screen Shot 2021-08-29 at 10 54 08

  • File pubspec.yaml added

flutter:
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  # === Generated Code Start ===
  # === Generated Code End ===
  • Run
javac BuildAssets.java
java BuildAssets
  • Open files pubspec.yaml and check result Screen Shot 2021-08-29 at 10 57 25

  • Run

java BuildAssets AssetImage svg_file.dart
  • Open files svg_file.dart and check result

Screen Shot 2021-08-29 at 11 18 19

Source code

https://github.com/ttpho/BuildAssets