'Flutter: Is it possible to set vertical alignment in text lines at height> 1.0?
All texts in Figma have some height, for example 1.5, but when I set that height to the TextStyle, all lines with the new height are aligned to the bottom.
If using Center or Align widgets - wrong result. Examples has bottom vertical alignment in their lines. Like on bottom screenshots.
[
Is there a possibility to set vertical alignment in flutter Text wiget for every line? Or maybe someone has some helpful tips to solve the problem?
Text(
'Example\nExample',
textAlign: TextAlign.center,
style:TextStyle(
height: 2.5,
fontSize: 20,
),
);
Solution:
As user1032613 suggested, such a solution helped.
final text = 'Example Example\nExample Example';
const double height = 2.5;
const double textSize = 16.0;
const double bottomPadding = (height * textSize - textSize) / 2;
const double baseline = height * textSize - height * textSize / 4;
final Widget textWidget = Container(
color: const Color(0xFFFFFFFF),
padding: const EdgeInsets.only(bottom: bottomPadding),
child: Baseline(
baselineType: TextBaseline.alphabetic,
baseline: baseline,
child: Text(
text,
style: const AppTextStyle(
height: height,
fontSize: textSize,
color: const Color(0xFFaa3a3a),
),
),
),
);
Solution 1:[1]
This is a quite common problem in Flutter when using custom fonts.
The solution our team currently uses is either use a Padding
or a Baseline
widget and manually tweak the text to make it appear vertically centered.
Solution 2:[2]
There is a property called leadingDistribution
which can be used for that:
Text(
'text',
style: TextStyle(
height: 2.0,
leadingDistribution: TextLeadingDistribution.even,
),
)
Solution 3:[3]
One way:
Align(
alignment: Alignment.center,
child: Text("Text"),
),
Another way:
Center(
child: Text("Hello World", textAlign: TextAlign.center,),
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | WSBT |
Solution 2 | intraector |
Solution 3 | Shahriar Nasim Nafi |