Flutter Gen은 자산, 폰트, 색상 및 기타 리소스에 대한 Dart 코드를 자동으로 생성함으로써 문자 기반 API를 제거하는 Flutter용 코드 생성기입니다. 컴파일 시점 검사를 제공하여 타입 안정성을 높이고 런타임 오류를 줄입니다. 개발자는 이미지, 문자열, 테마를 강력한 타입의 상수를 통해 접근할 수 있어 코드의 가독성과 유지보수성이 향상됩니다. 이 도구는 간단한 pub add 명령을 통해 Flutter 워크플로우에 원활하게 통합되며 macOS, Windows, Linux 등 여러 플랫폼을 지원합니다.
사용 사례
타입 안전한 자산 관리
자동 생성된 테마 및 색상 참조
개선된 문자열 로컬라이제이션
간편한 폰트 및 이미지 접근
UI 코드에서 부가적인 코드 감소
주요 기능
자산에 대한 타입화된 상수 생성
동적 테마 및 색상 생성을 지원합니다
Flutter 빌드 시스템과 통합
코드 완성 및 리팩토링 지원을 제공합니다
오타로 인한 런타임 오류를 최소화합니다
적합한 대상
대규모 플러터 애플리케이션
코드 품질을 우선시하는 팀
강력한 로컬라이제이션을 필요로 하는 프로젝트
풍부한 자산과 테마를 사용하는 개발자
유지보수 가능한 리소스 관리가 필요한 앱
고려 사항
설치 및 구성이 필요합니다
빌드 시간을 약간 증가시킬 수 있습니다
코드 생성 개념에 대한 이해가 필요합니다
최소한의 자산을 가진 매우 작은 프로젝트에는 적합하지 않습니다
정확한 자산 파일 구조에 의존합니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.
Widgetbuild(BuildContext context) {
returnImage.asset('assets/images/profile.jpeg');
}
// The following assertion was thrown resolving an image codec:// Unable to load asset: assets/images/profile.jpeg
FlutterGen also supports dart pub workspaces.
Run build_runner from the workspace root, and make sure each workspace member
that should be built has resolution: workspace in its pubspec.yaml.
FlutterGen will resolve each package from the active build target instead of the
process working directory, so package-local pubspec.yaml configuration and
output paths continue to work in workspace builds.
If generated source files were removed manually while .dart_tool/build is
still present, run dart run build_runner clean from the workspace root before
running build --workspace again. The current post-process builder flow can
re-materialize files reliably after a clean build, but a warm incremental build
may skip unchanged manifests.
For workspace builds, use Dart >=3.7.0 together with build_runner >=2.12.0.
Use --workspace to treat the config file as a workspace root pubspec and run
generation for each listed workspace member. Without --workspace, the command
generates for exactly one package.
When --workspace is enabled, the root pubspec.yaml is used only to discover
workspace members from its workspace: section. FlutterGen then switches to
each member package and loads that package's own pubspec.yaml and, if
present, its local build.yaml.
That means workspace-wide command execution behaves like this:
Root pubspec.yaml: selects which packages to visit.
Member pubspec.yaml: provides flutter and flutter_gen configuration.
Member build.yaml: overrides generator options for that member only.
The --build option is only available in single-package mode. In workspace
mode, put any overrides in each package's local build.yaml instead.
Configuration file
FlutterGen generates dart files based on the key flutter and flutter_gen of pubspec.yaml.
Default configuration can be found here.
When using build_runner, you can also configure generator options in the
target build.yaml. These builder options are applied on top of the
pubspec.yaml configuration for the current target.
# build.yaml# ...targets:$default:builders:flutter_gen_runner:# or flutter_genoptions:output:lib/build_gen/# Optional (default: lib/gen/)line_length:120# Optional
# pubspec.yamlflutter:assets:-assets/images/-assets/images/chip3/chip.jpg-assets/images/chip4/chip.jpg-path:assets/images/icons/paint.svg-path:assets/images/icons/transformed.svgtransformers:-package:vector_graphics_compiler-assets/images/icons/dart@test.svg-assets/json/fruits.json-assets/flare/Penguin.flr-assets/rive/vehicles.riv-pictures/ocean_view.jpg# Also include assets from deferred components# https://docs.flutter.dev/perf/deferred-componentsdeferred-components:-name:myDeferredComponentassets:-assets/images/another_image.jps-assets/videos/a_large_video.mp4
These configurations will generate assets.gen.dart under the lib/gen/ directory by default.
Flavored assets
Flutter supports
Conditionally bundling assets based on flavor.
Assets are only available with flavors if specified.
flutter_gen will generate the specified flavors for assets regardless the current flavor.
The flavors field accessible though .flavors, for example:
You can use parse_animation to generate more animation details.
It will automatically parse all animation information for GIF and WebP files,
including frames, duration, etc. As this option significantly increases generation time,
The option is disabled by default; enabling it will significantly increase the generation elapse.
flutter_gen:images:parse_animation:true# <- Add this line (default: false)# This option implies parse_metadata: true when parsing images.
For GIF and WebP animation, several new nullable field is added to the
generated class. For example:
If you are using SVG images with flutter_svg you can use the integration feature. This feature also supports using vector_graphics_compiler transformer and the produced code will use the AssetBytesLoader for such transformed assets.
Note: For lottie integration with .lottie and .tgs files, you must add a custom decoder via decoder parameter, see lottie's document for more information.
In other cases, the asset is generated as String class.
// If don't use the Integrations.final svg = SvgPicture.asset(Assets.images.icons.paint);
final json = await rootBundle.loadString(Assets.json.fruits);
FlutterGen also support generating other style of Assets class:
Just follow the doc Use a custom font to specify fonts, then FlutterGen will generate related dart files.
No other specific configuration is required. Ignore duplicated.
FlutterGen can generate a Color class based on the name attribute and the color hex value.
If the element has the attribute type, then a specially color will be generated.
[SEVERE] flutter_gen_runner:flutter_gen_runner on $package$:
Bad state: No element
[SEVERE] Failed after 16.0s
The you most likely have a customized build.yaml to configure the build runner. In that case, all you have to do is to add the pubspec.yaml as build source to your build.yaml
targets:$default:sources:include:-pubspec.yaml# add this line-...