[英]Centered Text inside a button with an icon in Flutter
我遇到了問題,我想制作一個按鈕(任何類型來實現此目的),該按鈕的圖標始終位於按鈕開頭的相同位置,並且與按鈕相比,按鈕的文本始終居中它下方的文本並始終以按鈕本身為中心,即使文本是動態的。 這就是我想要實現的目標:
按鈕文本根據下面的文本居中(保持不變),並與上面的按鈕居中,但如果按鈕文本動態變化,那么我有這些問題:
或者像這個:
任何想法如何解決這個問題?
我嘗試使用Expanded
小部件並添加 flex 屬性但失敗了。 我也嘗試了其他一些東西,但也失敗了......這是按鈕代碼:
TextButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.blue)),
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 1,
child: Icon(
Icons.keyboard_arrow_right_sharp,
color: Colors.white,
),
),
Expanded(
flex: 4,
child: Center(
child: Text(
"SOME TEXT",
style: TextStyle(color: Colors.white),
),
),
)
],
),
),
在此先感謝您的幫助!
有幾個選項可以做到這一點。 我將假設文本的大小可能會發生變化,因此您需要一個靈活的解決方案。
第一個選項是兩個選項中最明顯的,但如果文本太長會中斷。 訣竅是在按鈕的末尾添加一個空的 sizedBox,這樣文本就可以在展開的小部件中居中。
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: () {},
child: Row(
children: [
Icon(
Icons.keyboard_arrow_right_sharp,
color: Colors.white,
size: 24,
),
Expanded(
child: Center(
child: Text(
"SOME TEXT",
style: TextStyle(
color:Colors.white,
),
),
),
),
SizedBox(
width: 24, // width of the icon
),
],
),
);
另一種選擇是使用堆棧小部件。 這樣,如果文本太長,它會與圖標重疊,但不太可能會溢出按鈕。
TextButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: () {},
child: Stack(
children: [
Positioned(
left: 0,
child: Icon(
Icons.keyboard_arrow_right_sharp,
color: Colors.white,
size: 24,
),
),
Center(
child: Text(
"SOME TEXT",
style: TextStyle(
color:Colors.white,
),
),
),
],
),
);
讓我們討論一下您的代碼:從開始使用帶有主軸對齊的行使元素從可用區域開始。 然后我建議使用SizedBox
根據需要在元素之間SizedBox
出一些間距並調整它的寬度。
TextButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.blue)),
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.start, // here the issue
children: [
Expanded(
flex: 1,
child: Icon(
Icons.keyboard_arrow_right_sharp,
color: Colors.white,
),
),
SizedBox(width: MediaQuery.of(context).size.width * 0.08, // change this value as you want 0.08 or 0.1 ...etc
),
Expanded(
flex: 4,
child: Center(
child: Text(
"SOME TEXT",
style: TextStyle(color: Colors.white),
),
),
)
],
),
),
有關更多信息,請閱讀此文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.