FlutterGen Code Generator | Sailesh Verma

FlutterGen Code Generator

While working with flutter, to load assets in your Flutter app, you have to reference the asset using path strings, which is not safe. As a Flutter developer, you have no choice but to refer to them using strings directly in your code. Working with images, for instance, is not easy because you have to refer to them by their path string.

FlutterGen, a Flutter code generator for your assets that help remove all string-based APIs in your app.


Working with Assets:

An asset is any file bundled and deployed with your application for accessing at runtime. Assets can be in the following forms:

- Images

- Animations

- Fonts

- Configuration files

- Static data for example text or JSON files

To load assets in your Flutter app, you have to reference the asset using path strings, The FlutterGen package helps remove all string-based APIs in your app by generating code for all your assets.

Working with FlutterGen is super easy:

1. You declare assets in your pubspec.yaml file as you would normally do; no other configuration is needed

2. FlutterGen will then generate the related Dart files under the lib/gen directory by default

3. You can then load your assets using the classes generated.

The following are available parsers you can configure:

Assets — this configuration generates the assets.gen.dart file under lib/gen

Fonts — this configuration generates the fonts.gen.dart file under lib/gen

Colors — this configuration generates the colors.gen.dart file under lib/gen

Setting up FlutterGen

We will install it as part of build_runner.

Add build_runner and flutter_gen as part of your dev_dependencies in the pubspec.yaml file:

dev_dependencies: build_runner: flutter_gen_runner:

Specify assets in your pubspec.yaml file as shown:

flutter: uses-material-design: true assets: - assets/images/ - assets/video/ - assets/animations/ - assets/json/

Generate code for assets

Run flutter packages pub run build_runner build in your root app directory. This command will generate the files for related assets in the lib/gen folder. In this case, assets files is generated :

assets.gen.dart — contains generated code for your image, video, animation, and JSON assets

You will have to add the file imports to the relevant layout files:

import '../gen/assets.gen.dart';import '../gen/fonts.gen.dart';

For your case, the image path is assets/images/add_color.png. You can load your image in the following formats:

Assets.images.addcolor — implements the AssetImage classAssets.images.addcolor.image(...) — return Image classAssets.images.addcolor.path — return path string