How to Manage Assets in Flutter Using Flutter_Gen

by SkillAiNest

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

  1. Conditions

  2. Why flutter? Advantages of Automated Asset Management

  3. Step-by-step implementation guide

  4. Important Considerations

  5. Further reading

  6. The result

Conditions

Before starting, make sure you have the following installed:

  1. Flutter SDK: You must have the latest stable version of the filter installed and configured. You can check with your installation flutter --version.

  2. 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:

  1. Type of protection: This is perhaps the most important advantage. Instead of delicate wire paths, flutter_gen Creates 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_gen This ensures that your asset references are always correct and up-to-date, drastically reducing the chance of runtime errors related to incorrect paths.

  2. 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.

  3. Better support: In a team environment, flutter_gen Facilitates 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:

  1. dependencies Section: flutter_gen: ^5.12.0: This is the main package that provides ready-made asset classes for your Flutter application.

  2. dev_dependencies Section:

    • build_runner: ^2.4.13: build_runner is a powerful package that provides a solid way to generate files in a Flutter project. flutter_gen_runner Usage build_runner To implement its code generation logic.

    • flutter_gen_runner: ^5.12.0: This package contains the actual code generator that scans you pubspec.yaml and asset folders to create type-safe asset references.

  3. flutter Section:

    • assets:: This section is very important for specifying which directories contain your assets. We have entered assets/for , for , for , . assets/images/and assets/icons/ To ensure that all assets within these folders are bundled with your application.

    • fonts:: This section declares your custom fonts. Here, we have registered Roboto Specifying the font family, path Roboto-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) within assets/fonts/ Folder

  • Create icons: Place your icon files (for example, file_add.png) within assets/icons/ Folder

  • Creating images: Place your image files (for example, img.png) within assets/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:

  1. flutter pub get: Retrieves all packages declared in u pubspec.yaml file, including flutter_genfor , for , for , . build_runnerand flutter_gen_runner.

  2. flutter pub run build_runner build: Request build_runnerwhich in turn is activated flutter_gen_runner. The runner will scan you pubspec.yaml And assets/ 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,

  1. $AssetsIconsGen And $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 one AssetGenImage Objection

  2. Assets Class: This is the primary entry point for accessing all your generated assets. It provides a stable example $AssetsIconsGen And $AssetsImagesGen (For example, Assets.iconsfor , for , for , . Assets.images)

  3. AssetGenImage Class: This utility class encapsulates the asset path and provides convenience methods image() To make one directly Image Widgets and more provider() to get one ImageProvider. path Gator 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:

  1. import '../gen/assets.gen.dart';: This line imports generated assets.gen.dart file, making all your typesafe image and icon assets available.

  2. Image.asset(Assets.images.img.path): Same as hardcoded string Image.asset('assets/images/img.png')now we use Assets.images.img.path. It is type-safe and benefits from IDE autotemplate, preventing errors and improving readability.

  3. Image.asset(Assets.icons.fileAdd.path): Similarly, icons are accessed Assets.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:

  1. import 'gen/fonts.gen.dart';: It imports generated fonts.gen.dart file, giving you access to FontFamily Class

  2. theme: ThemeData(fontFamily: FontFamily.roboto): Here, we are applying Roboto Our entire font family MaterialApp Using a theme FontFamily.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.

Application launched

Important Considerations

There are a couple of things to note here:

  1. Whenever you add, remove, or rename assets in your assets/ Folders, or edit the assets declaration in it pubspec.yamlyou It is necessary Reissue the code generation commands:

     flutter pub get
     flutter pub run build_runner build
    
  2. For a more seamless experience, you can use watch command with build_runner. It will automatically regenerate your asset files whenever changes are detected:

     flutter pub run build_runner watch
    

    Keep 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.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro