I’m wondering if using style files with methods like these makes sense:
static TextStyle defaultStyle() {
return const TextStyle(
fontFamily: 'Ubuntu',
letterSpacing: 0,
);
}
static TextStyle display1() {
return defaultStyle().copyWith(
color: AppColors.black900,
fontSize: 57.0,
fontWeight: FontWeight.w900,
);
}
We keep these values in one place, but when using them, we can’t use const before the widgets.
Result:
Text(
'Hello',
textAlign: TextAlign.center,
style: AppTextStyles.display1().copyWith(color: AppColors.gray500),
),
Instead of:
const Text(
'Hello',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Ubuntu',
letterSpacing: 0,
color: AppColors.black900,
fontSize: 57.0,
fontWeight: FontWeight.w900,
),
),
I’ve noticed this in every project I’ve watched so far. Isn’t this a mistake that affects the performance of the application?
2
Answers
Well, it isn’t a mistake. It does have it’s own effect on performance but they are so small and almost non-existent.
One reason why many opt-in for this sort of implementation is to avoid repetitive-coding, a situation where you repeat something you have used implemented somewhere in your code before. Imagine a 5-line code for the text-style been re-used in 30 different places, just because there’s a tiny bit of change in the colour in those cases; that would be a whooping 110+ additional lines of code.
Another reason is to avoid inconsistency and promote code maintenance in your code. Imagine, checking through the UI Designs you realised the text-size should be
24px
not22px
, you’s need to go through each of those 30 different files or points to fix it manually; and trust me that can get very troublesome.Lastly, although creating modular codes in this way saves one a lot of hassle; it is completely impractical and redundant to do that for a particular code-snippet you are completely sure will be used once. The key is to be smart about it.
As the other answer suggested, don’t stress about it, it is NOT a big performance issue this will cause especially if your application is not that big
As a work around I will suggest this type of arrangement, yes it might create a bunch more of boilerplate but if you want to squeeze that last bit of performance you can take such a tradeoff