ThemeTailor는 Flutter 3.0용 코드 생성기로, ThemeExtension 클래스를 사용하여 테마 확장 및 테마를 만드는 과정을 간소화합니다. 정의된 속성 기반으로 테마 관련 코드를 생성하여 BuildContext와 ThemeData에서 일관된 테마 설정을 가능하게 합니다. 이 도구는 라이트 모드와 다크 모드 구성 모두를 지원하며, Flutter 앱 내에서 테마 관리를 간편하게 만듭니다. pub add를 통해 기존 프로젝트에 원활하게 통합되며, 새로운 ThemeExtension API를 활용해 개선된 사용자 지정과 확장성을 제공합니다.
사용 사례
다이나믹 테마 생성
테마 확장 생성 자동화
라이트 모드와 다크 모드 전환 지원
테마 속성 관리 간소화
컨텍스트 기반 테마 활성화
다중 플랫폼 간 UI 일관성 개선
주요 기능
테마 확장에 대한 코드 생성
BuildContext 및 ThemeData를 지원합니다
라이트 모드와 다크 모드 통합
속성 기반 테마 정의
크로스 플랫폼 호환성
간편한 pub add 통합
적합한 대상
ThemeExtension를 사용하는 Flutter 개발자
복잡한 테마를 관리하는 팀
동적 테마 지원이 필요한 앱
다양한 플랫폼을 대상으로 하는 개발자
UI 일관성에 중점을 둔 프로젝트
Flutter 3.0+ 최선의 실천 방법을 채택하는 사람들
고려 사항
Flutter 3.0 이상이 필요합니다
코드 생성을 위해 build_runner가 필요합니다
테마 속성 수동 구성
테마 관련 코드 생성에 제한됨
소스 코드 구조에 따라 다릅니다
구조화된 프로젝트 설정에서 가장 잘 사용됩니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Welcome to Theme Tailor, a code generator and theming utility for supercharging Flutter ThemeExtension classes introduced in Flutter 3.0! The generator helps to minimize the required boilerplate code.
Flutter 3.0 introduces a new way of theming applications using theme extensions in ThemeData. To declare a theme extension, you need to create a class that extends ThemeData, define its constructor and fields, implement the "copyWith" and "lerp" methods, and optionally override the "hashCode," "==" operator, and implement the "debugFillProperties" method. Additionally you may want to create extensions on BuildContext or ThemeData to access newly created themes.
All of that involves extra coding work that is time-consuming and error-prone, which is why it is advisable to use a generator.
No code generation
@TailorMixin
The @TailorMixin annotation generates a mixin with an implementation of the ThemeExtension class. It adopts a syntax familiar to standard ThemeExtension classes, allowing for enhanced customization of the resulting class.
It's worth noting that choosing either the @Tailor or @TailorMixin generator doesn't restrict you from using the other in the future.
In fact, the two generators can be used together to provide even more flexibility in managing your themes. Ultimately, both generators offer strong solutions for managing themes and can be used interchangeably to provide the level of customization that best suits your project.
How to use
Install
ThemeTailor is a code generator and requires build_runner to run.
Make sure to add these packages to the project dependencies:
build_runner tool to run code generators (dev dependency)
theme_tailor this package - theming utility (dev dependency)
ThemeTailor is a generator for annotation that generates code in a part file that needs to be specified. Make sure to add the following imports and part directive in the file where you use the annotation.
Make sure to specify the correct file name in a part directive. In the example below, replace "name" with the file name.
To run the code generator, run the following commands:
flutter run build_runner build --delete-conflicting-outputs
Create Theme class
@TailorMixin:
Annotate your class with @TailorMixin() and mix it with generated mixin, generated mixin name starts with _$ following your class name and ending with "TailorMixin" suffix.
Example
my_theme.dart
import'package:flutter/material.dart';
import'package:theme_tailor_annotation/theme_tailor_annotation.dart';
part'my_theme.tailor.dart';
@TailorMixin()
classMyThemeextendsThemeExtension<MyTheme> with_$MyThemeTailorMixin{
/// You can use required / named / optional parameters in the constructor// const MyTheme(this.background);// const MyTheme([this.background = Colors.blue])constMyTheme({requiredthis.background});
finalColor background;
}
The following code snippet defines the "_$MyThemeTailorMixin" theme extension mixin.
mixin "_$MyThemeTailorMixin" on ThemeExtension<MyTheme>
There is getter "background" field of Color type
Implements "copyWith" from ThemeExtension, with a nullable argument "background" of type "Color"
Implements "lerp" from ThemeExtension, with the default lerping method for the "Color" type
Overrites "hashCode" and "==" operator
Additionally theme_tailor_annotation by default generates extension on ThemeData (to change that set themeGetter to ThemeGetter.none or use @TailorMixinComponent annotation)
"MyThemeThemeDataProps" extension on "ThemeData" is generated
getter on "background" of type "Color" is added directly to "ThemeData"
Change generated extensions
By default, "@tailorMixin" will generate an extension on "ThemeData" and expand theme properties as getters. If this is an undesired behavior, you can disable it by changing the "themeGetter" property in the "@TailorMixin" or using the "@TailorMixinComponent" annotation.
@TailorMixin(themeGetter: ThemeGetter.none)
@TailorMixinComponent() // This automatically sets ThemeGetter.none
"ThemeGetter" has several variants for generating common extensions to ease access to the declared themes.
It might be beneficial to split them into smaller parts, where each part is responsible for the theme of one component. You can think about it as modularization of the theme. ThemeExtensions allow easier custom theme integration with Flutter ThemeData without creating additional Inherited widgets handling theme changes. It is especially beneficial when
Creating design systems,
Modularization of the application per feature and components,
Create a package that supplies widgets and needs more or additional properties not found in ThemeData.
Structure of the application's theme data and its extensions. "chatComponentsTheme" has nested properties.
ThemeData: [] # Flutter's material widgets propsThemeDataExtensions:-ChatComponentsTheme:-MsgBubble:-Bubble:myBubble-Bubble:friendsBubble-MsgList: [foo, bar, baz]
Use "@tailorMixin" / "@TailorMixin" annotations if you may need additional extensions on ThemeData or ThemeContext.
Use "@tailorMixinComponent" / "@TailorMixinComponent" if you intend to nest the theme extension class and do not need additional extensions. Use this annotation for generated themes to allow the generator to recognize the type correctly.
Example for @TailorMixin annotation:
@tailorMixinclassChatComponentsThemeextendsThemeExtension<ChatComponentsTheme> with_$ChatComponentsTheme{
/// TODO: Implement constructorfinalMsgBubble msgBubble;
finalMsgList msgList;
finalNotGeneratedExtension notGeneratedExtension;
}
@tailorMixinComponentclassMsgBubbleextendsThemeExtension<MsgBubble> with_$MsgBubble{
/// TODO: Implement constructorfinalBubble myBubble;
finalBubble friendsBubble;
}
/// The rest of the classes as in the previous example but following @TailorMixin pattern/// [...]
ThemeTailor will attempt to provide lerp method for types like:
Color
Color?
TextStyle
TextStyle?
In the case of an unrecognized or unsupported type, the generator provides a default lerping function (That does not interpolate values linearly but switches between them).
You can specify a custom the lerp function for the given type (Color/TextStyle, etc.) or property by extending "ThemeEncoder" class from theme_tailor_annotation
Example of adding custom encoder for an int.
my_theme.dart
import'dart:ui';
classIntEncoderextendsThemeEncoder<int> {
constIntEncoder();
@overrideintlerp(int a, int b, double t) {
returnlerpDouble(a, b, t)!.toInt();
}
}
Use it in different ways:
/// 1 Add it to the encoders list in the @TailorMixin() annotation@TailorMixin(encoders: [IntEncoder()])
classTheme1extendsThemeExtension<Theme1> with_$Theme1TailorMixin{}
/// 2 Add it as a separate annotation below @TailorMixin() or @tailorMixin annotation@tailorMixin@IntEncoder()
classTheme2extendsThemeExtension<Theme2> with_$Theme2TailorMixin{}
/// 3 Add it below your custom tailor annotationconst appTailorMixin = TailorMixin(themeGetter: ThemeGetter.onBuildContext);
@appTailorMixin@IntEncoder()
classTheme3extendsThemeExtension<Theme3> with_$Theme3TailorMixin{}
/// 4 Add it on the property@tailorMixinclassTheme4extendsThemeExtension<Theme4> with_$Theme4TailorMixin{
// TODO constructor required@IntEncoder()
finalColor background;
}
/// 5 IntEncoder() can be assigned to a variable and used as an annotation/// It works for any of the previous examplesconst intEncoder = IntEncoder();
@tailorMixin@intEncoderclassTheme5extendsThemeExtension<Theme5> with_$Theme5TailorMixin{}
The generator chooses the proper lerp function for the given field based on the order:
annotation on the field
annotation on top of the class
property from encoders list in the "@TailorMixin" annotation.
Custom-supplied encoders override default ones provided by the code generator. Unrecognized or unsupported types will use the default lerp function.
To see more examples of custom theme encoders implementation, head out to example: theme encoders
Flutter diagnosticable / debugFillProperties
To add support for Flutter diagnosticable to the generated ThemeExtension class, import Flutter foundation. Then create the ThemeTailor config class as usual.
For @TailorMixin() you also need to mix your class with DiagnosticableTreeMixin
@TailorMixin()
classMyThemeextendsThemeExtension<MyTheme>
withDiagnosticableTreeMixin, _$MyThemeTailorMixin{
/// Todo: implement the class
}
Json serialization
The generator will copy all the annotations on the class and the static fields, including: "@JsonSerializable", "@JsonKey", custom JsonConverter(s), and generate the "fromJson" factory. If you wish to add support for the "toJson" method, you can add it in the class extension:
To serialize nested themes, declare your config classes as presented in the Nesting generated theme extensions, modular themes, design systems. Make sure to use proper json_serializable config either in the annotation on the class or your config "build.yaml" or "pubspec.yaml". For more information about customizing build config for json_serializable head to the json_serializable documentation.
@JsonSerializable(explicitToJson: true)
Build configuration
The generator will use properties from build.yaml or default values for null properties in the @TailorMixin annotation.
String For custom Theme if you don't want use Material's Theme. Example: FluentTheme
theme_data_class_name
themeDataClassName
null
String For custom ThemeData if you don't want use Material's ThemeData FluentThemeData
format
—
true
bool Formats generated .tailor.dart output. Set to false to leave the output unformatted and add // dart format off, so later project-wide formatting does not change it.
If you're not using Material, feel free to modify the theme_getter extension to another option. For instance, you can use it with a different theme, like FluentTheme.