Managing assets like images, icons, and fonts in a Flutter project can quickly become a tedious task, especially as your application grows. Manual reference is prone to typos, introduces maintenance overhead, and can hinder team collaboration.
fortunately, flutter_gen The package provides an elegant solution by automating asset generation, type safety and bringing a streamlined workflow to your development process.
This comprehensive guide will walk you through setting up a flutter project flutter_genexplaining each step and code block in detail so you can easily integrate this powerful tool into your projects.
Table of Contents
Conditions
Before starting, make sure you have the following installed:
Flutter SDK: You must have the latest stable version of the filter installed and configured. You can check with your installation
flutter --version.A code editor: Visual Studio Code with the Flutter extension is recommended, but any suitable IDE will work.
Why? flutter_gen? Advantages of Automated Asset Management
flutter_gen Flutter offers a number of benefits that can significantly improve your asset management experience:
Type of protection: This is perhaps the most important advantage. Instead of delicate wire paths,
flutter_genCreates strong type classes for each asset type (images, icons, fonts). This eliminates runtime errors caused by typos and provides better code completion in your IDE, which facilitates asset discovery.
Fewer errors: Manual asset path management is a common source of bugs.flutter_genThis ensures that your asset references are always correct and up-to-date, drastically reducing the chance of runtime errors related to incorrect paths.Better code maintenance: As your project scales, finding and updating assets can become a nightmare. Generated asset classes serve as a central, ship-to-ship reference point, making it easy to locate and edit assets without wading through countless files.
Better support: In a team environment,
flutter_genFacilitates collaboration. Team members can intuitively discover and use assets through code completion, minimizing communication overhead related to asset paths and ensuring consistency across the code base.
Step-by-step implementation guide
Let’s dive into setting up your flutter plan flutter_gen.
1. Project Setup
Create a new Fluffy project:
Start by creating a fresh flutter project. Open your terminal or command prompt and run:
flutter create flutter_auto_assets
cd flutter_auto_assets
This command creates a new Flutter project named flutter_auto_assets and navigates you to its directory.
Add dependencies:
open pubspec.yaml The file is located at the root of your project. This file manages your project’s dependencies and assets. add flutter_gen And flutter_gen_runner Packages, as well build_runneryour pubspec.yaml As shown below:
name: flutter_auto_assets
description: A flutter app demonstrating asset auto generation
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.8.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
flutter_gen: ^5.12.0
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.4.13
flutter_gen_runner: ^5.12.0
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
- assets/icons/
fonts:
- family: Roboto
fonts:
- asset: assets/fonts/Roboto-Regular.ttf
Description of pubspec.yaml additions:
dependenciesSection:flutter_gen: ^5.12.0: This is the main package that provides ready-made asset classes for your Flutter application.dev_dependenciesSection:build_runner: ^2.4.13:build_runneris a powerful package that provides a solid way to generate files in a Flutter project.flutter_gen_runnerUsagebuild_runnerTo implement its code generation logic.flutter_gen_runner: ^5.12.0: This package contains the actual code generator that scans youpubspec.yamland asset folders to create type-safe asset references.
flutterSection:assets:: This section is very important for specifying which directories contain your assets. We have enteredassets/for , for , for , .assets/images/andassets/icons/To ensure that all assets within these folders are bundled with your application.fonts:: This section declares your custom fonts. Here, we have registeredRobotoSpecifying the font family, pathRoboto-Regular.ttf.
2. Manage your assets
Create the following folder structure inside your project’s root directory. This organization helps you discover your assets cleanly and easily.
flutter_auto_assets/
├── assets/
│ ├── fonts/
│ │ └── Roboto-Regular.ttf
│ ├── icons/
│ │ └── file_add.png
│ └── images/
│ └── img.png
├── lib/
│ └── main.dart
└── pubspec.yaml
A few things to note here:
Creating Fonts: Place your font files (for example,
Roboto-Regular.ttf) withinassets/fonts/FolderCreate icons: Place your icon files (for example,
file_add.png) withinassets/icons/FolderCreating images: Place your image files (for example,
img.png) withinassets/images/Folder
3. Run code generation
Now it’s time to create type-safe asset classes. Open your terminal in the root directory of the project and execute the following commands:
flutter pub get
flutter pub run build_runner build
This command does what it does:
flutter pub get: Retrieves all packages declared in upubspec.yamlfile, includingflutter_genfor , for , for , .build_runnerandflutter_gen_runner.flutter pub run build_runner build: Requestbuild_runnerwhich in turn is activatedflutter_gen_runner. The runner will scan youpubspec.yamlAndassets/directory, then create the necessary Dart files containing your typesafe asset references.
After running these commands, you should have a new folder named gen Created within you lib Directory This gen will contain the folder assets.gen.dart And fonts.gen.dart.
4. Explore the generated files
Let’s take a look at the files flutter_gen Creates for you.
fonts.gen.dart: This file contains the auto-generated FontFamily class, which provides a type-safe way to refer to your custom font.
class FontFamily {
FontFamily._();
static const String roboto = 'Roboto';
}
Here, a FontFamily A class is created and declared in u for each font family pubspec.yaml (For example, Roboto), and a fixed constant string field is created (for example, roboto) This allows you to reference your own font family FontFamily.robototo ensure accuracy.
assets.gen.dart: This file contains auto-generated classes for your image and icon assets.
import 'package:flutter/widgets.dart';
class $AssetsIconsGen {
const $AssetsIconsGen();
AssetGenImage get fileAdd => const AssetGenImage('assets/icons/file_add.png');
List get values => (fileAdd);
}
class $AssetsImagesGen {
const $AssetsImagesGen();
AssetGenImage get img => const AssetGenImage('assets/images/img.png');
List get values => (img);
}
class Assets {
Assets._();
static const $AssetsIconsGen icons = $AssetsIconsGen();
static const $AssetsImagesGen images = $AssetsImagesGen();
}
class AssetGenImage {
const AssetGenImage(this._assetName);
final String _assetName;
Image image({
Key? key,
AssetBundle? bundle,
ImageFrameBuilder? frameBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? scale,
double? width,
double? height,
Color? color,
Animation<double>? opacity,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
String? package,
FilterQuality filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) {
return Image.asset(
_assetName,
key: key,
bundle: bundle,
frameBuilder: frameBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
scale: scale,
width: width,
height: height,
color: color,
opacity: opacity,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
package: package,
filterQuality: filterQuality,
cacheWidth: cacheWidth,
cacheHeight: cacheHeight,
);
}
ImageProvider provider({
AssetBundle? bundle,
String? package,
}) {
return AssetImage(
_assetName,
bundle: bundle,
package: package,
);
}
String get path => _assetName;
String get keyName => _assetName;
}
In this code,
$AssetsIconsGenAnd$AssetsImagesGen: These classes represent your icon and image directories respectively. Each asset in these directories gets a getter (for example,fileAddfor , for , for , .img) which returns oneAssetGenImageObjectionAssetsClass: This is the primary entry point for accessing all your generated assets. It provides a stable example$AssetsIconsGenAnd$AssetsImagesGen(For example,Assets.iconsfor , for , for , .Assets.images)AssetGenImageClass: This utility class encapsulates the asset path and provides convenience methodsimage()To make one directlyImageWidgets and moreprovider()to get oneImageProvider.pathGator provides a raw asset path if needed.
5. Using Generated Assets in Your Code
Now that your assets are type-safe and easily accessible, let’s integrate them into your Flutter application.
First, create a screens folder within you lib Directory Next, create a new file named entry_screen.dart inside lib/screens folder and paste the following code:
lib/screens/entry_screen.dart:
import 'package:flutter/material.dart';
import '../gen/assets.gen.dart';
class EntryScreen extends StatelessWidget {
const EntryScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: (
Image.asset(Assets.images.img.path),
const SizedBox(height: 10),
const Text(
'Flutter Gen Assets',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 10),
Image.asset(Assets.icons.fileAdd.path),
),
),
),
);
}
}
what is happening entry_screen.dart:
import '../gen/assets.gen.dart';: This line imports generatedassets.gen.dartfile, making all your typesafe image and icon assets available.Image.asset(Assets.images.img.path): Same as hardcoded stringImage.asset('assets/images/img.png')now we useAssets.images.img.path. It is type-safe and benefits from IDE autotemplate, preventing errors and improving readability.Image.asset(Assets.icons.fileAdd.path): Similarly, icons are accessedAssets.icons.fileAdd.path.
Next, make your edits main.dart file to use EntryScreen and generated fonts.
lib/main.dart:
import 'gen/fonts.gen.dart';
import 'screens/entry_screen.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(fontFamily: FontFamily.roboto),
debugShowCheckedModeBanner: false,
home: const EntryScreen(),
);
}
}
i main.dart:
import 'gen/fonts.gen.dart';: It imports generatedfonts.gen.dartfile, giving you access toFontFamilyClasstheme: ThemeData(fontFamily: FontFamily.roboto): Here, we are applyingRobotoOur entire font familyMaterialAppUsing a themeFontFamily.roboto. This is a safe way to refer to your custom font.
Your request is running
Save all your changes and run your flutter application:
flutter run
You should see your application launch, displaying the image and icon, all organized efficiently and type-safely. flutter_gen.

Important Considerations
There are a couple of things to note here:
Whenever you add, remove, or rename assets in your
assets/Folders, or edit the assets declaration in itpubspec.yamlyou It is necessary Reissue the code generation commands:flutter pub get flutter pub run build_runner buildFor a more seamless experience, you can use
watchcommand withbuild_runner. It will automatically regenerate your asset files whenever changes are detected:flutter pub run build_runner watchKeep running this command in a separate terminal window during development.
The result
By integrating flutter_gen In your Flutter workflow, you unlock a superior asset management experience characterized by type safety, fewer errors, better retention, and better collaboration.
This guide gives you a solid foundation for effectively leveraging this powerful package, making your Flutter development journey smoother and more robust.
Further reading
To explore more advanced configurations and features flutter_genrefer to Official flutter_gen Package documentation page.