Gerador de código para classes ThemeExtension do Flutter 3.0. O gerador pode criar temas e extensões em BuildContext ou ThemeData com base nas listas das propriedades do tema
Orientação gerada a partir de informações públicas. Apenas para referência.
ThemeTailor é um gerador de código para o Flutter 3.0 que simplifica a criação de extensões de tema e temas usando classes ThemeExtension. Ele gera código relacionado ao tema com base em propriedades definidas, permitindo uma tematização consistente em BuildContext e ThemeData. A ferramenta suporta configurações de modo claro e escuro, agilizando a gestão de temas em aplicativos Flutter. Integra-se perfeitamente a projetos existentes por meio do pub add e aproveita a nova API ThemeExtension para personalização aprimorada e escalabilidade.
Casos de uso
Gerando temas dinâmicos
Automatizando a criação de extensão de tema
Suporte para alternância entre modo claro e escuro
Simplificando a gestão de propriedades do tema
Habilitar tematização baseada em contexto
Padronização da consistência da interface entre plataformas
Principais recursos
Geração de código para ThemeExtension
Suporta BuildContext e ThemeData
Integração de modo claro e escuro
Definição de tema orientada por propriedades
Compatibilidade multiplataforma
Integração fácil do pub add
Indicado para
Desenvolvedores Flutter usando ThemeExtension
Equipes gerenciando temas complexos
Aplicativos que exigem suporte a tema dinâmico
Desenvolvedores direcionados para múltiplas plataformas
Projetos focados na consistência da interface do usuário
Aqueles que adotam as melhores práticas do Flutter 3.0+
Considerações
Requer Flutter 3.0 ou superior
Precisa do build_runner para geração de código
Configuração manual de propriedades do tema
Limitado à geração de código relacionada ao tema
Dependente da estrutura do código-fonte
Melhor usado em configurações de projeto estruturadas
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
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.