As a beginner in the development field, I’ve been endeavoring to grasp the concepts of creating responsive and adaptive apps. However, I’m encountering some confusion. One particular question arises: Should the text resize when the device size changes? I’ve sought clarification through various YouTube videos where different font sizes are employed for distinct devices such as mobile, tablet, and desktop, like this.
LayoutBuilder(
builder: (context, constraints) {
// mobile ...................................................................
if (constraints.maxWidth < 600) {
return const Text(
'Example',
style: TextStyle(
fontSize: 20,
),
);
// tablet .................................................................
} else if (constraints.maxWidth > 600 && constraints.maxWidth < 800) {
return const Text(
'Example',
style: TextStyle(
fontSize: 25,
),
);
// mobile .................................................................
} else {
return const Text(
'Example',
style: TextStyle(
fontSize: 30,
),
);
}
},
);
But, mobile devices can have many screen sizes, for example. However, they use a constant size for all the mobile devices (fontSize: 20). I cannot understand this. Please clear my doubt and tell me which is the best method to achieve responsiveness?
2
Answers
You’re on the right track, but you’ll have to use a mix of solutions, including your example, to achieve the results you want.
There are a couple of more classes you should add to your toolbox:
1. FractionallySizedbox
Allows you to size based off a
factor
size e.g. percent.More info: https://api.flutter.dev/flutter/widgets/FractionallySizedBox-class.html
2. MediaQuery
MediaQuery
gives you a LOT of info about the device such as size, orientation, if the user changed the default font size, etc.More info: https://api.flutter.dev/flutter/widgets/MediaQuery-class.html
For achieving the responsiveness in text, you can use textScalefactor as given below:
you can use media query, expanded, and Flexible widgets. and you can make your own sizer tool like this.
for e.g:
Now, you can use it in any widget for allocating the size of Widgets in percent of the screen. you will achieve the same responsiveness with the same code for different screen devices.
If you find this Useful. Do share and upvote this trick.