How to support text size accessibility in Flutter like Android sp size and iOS Dynamic Type
Flutter has accessibility support for larger fonts built in by default. You can override this behavior by specifying a textScaleFactor
, which Flutter normally uses to apply the user selected text size.
You can test this by comparing two Text widgets, the second one with textScaleFactor
set to 1.0
. The default font size for both of them is 14.0 logical pixels.
Widget _myWidget() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Some sample text'),
Text('Some sample text', textScaleFactor: 1.0),
],
);
}
You can get the current text scale factor like this:
final scale = MediaQuery.of(context).textScaleFactor;
Android
In Android settings Accessibility > Font size choose the smallest size.
Do it again and choose the largest size.
Notice that the first Text widget text changed sizes, but second one with the textScaleFactor
override didn't.
iOS
In iOS go to Settings > General > Accessibility > Larger text and choose the smallest option.
And again with the largest setting:
Comments
-
Suragch about 2 years
In Android you can set the font size using Scale-independent Pixels (sp) to take into account user font size preferences chosen in the settings.
android:textSize="26sp"
In iOS you can use Dynamic Type to so something similar.
label.font = UIFont.preferredFont(forTextStyle: .body) label.adjustsFontForContentSizeCategory = true
How do you do the same thing in Flutter?
-
Joe Lapp over 4 yearsBut how do I variably control text size while remaining accessible? As you said,
textScaleFactor
overrides the accessibility controls. -
Suragch over 4 years@JoeLapp, You can still set the text size as normal by setting the style property on Text (
style: TextStyle(fontSize: 30)
). This allows you to control the text size while remaining accessible. -
Joe Lapp over 4 yearsOh! Somehow I came to assume that
fontSize
overridestextScaleFactor
, but now I see that it doesn't. Thanks! api.flutter.dev/flutter/painting/TextStyle/fontSize.html -
Joe Muller about 3 yearsIs there a way to get the current text scale? I'd like to rearrange my widgets if the scale is too big
-
Joe Muller about 3 yearsI think I found it. You can use MediaQuery.of(context).textScaleFactor
-
Suragch about 3 years@JoeMuller, Nice! Good to know. I updated the answer.