Back to all posts

Text Scaler in Flutter!

So we all know that flutter recently deprecated textScaleFactor by replacing it with textScaler. So now we will learn what exactly textScaler is and also the migration guide from textScaleFactor to textScaler.

Text Scaler

A TextScaler in Flutter is a class that controls how text should be scaled for better readability. It allows you to adjust the size of text in a more flexible way, making it easier to read, especially for users who need larger or smaller text.

Using TextScaler

1. Creating a Text Scaler

You can create a linear text scaler using TextScaler.linear(double scale).

Text(
'Linear Text Scaler',
textScaler: TextScaler.linear(1.2) //Previously: textScaleFactor: 1.2
)

2. Setting a Text Scaler in Media Query

You can set a TextScaler for a widget subtree using MediaQuery.

MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(1.2)),
child: YourTextWidget(),
)

3. Retrieving TextScaler

Use MediaQuery.textScalerOf(context) to retrieve the current text scaler.

Text(
"Flutter Text Scaler",
textScaler: MediaQuery.textScalerOf(context)
)

If you don't want the font scale to cross certain number, we can use clamp.

Text(
"Clamp Text Scaler",
textScaler: MediaQuery.textScalerOf(context)
                        .clamp(minScaleFactor: 1.0, maxScaleFactor: 1.2),
)

Scale Font Size using Text Scaler

final TextScaler textScaler = MediaQuery.textScalerOf(context);
final double baseFontSize = 20;

final double scaledFontSize = textScaler.scale(baseFontSize);

Text(
"Scaled Font Size",
style: TextStyle(fontSize: scaledFontSize),
)

Conclusion

In conclusion, the transition from textScaleFactor to textScaler in Flutter represents a significant improvement in managing text scaling, providing developers with more flexibility and precision. By adopting textScaler, you can enhance the readability of your app's text, accommodating users' preferences and accessibility needs more effectively.

References

  • Text Scaler
  • Deprecate textScaleFactor in favor of TextScaler