![](/img/trans.png)
[英]How to change the label text color when text filed is focused when more than one textfield used in flutter
[英]Flutter TextField label is outside of background when focused
標題應該說明一切。 不過,為了更好地理解,這里有一些圖片。
它應該是什么樣子(Google Material Components):
但請忽略圖片的底部邊框“它應該是什么樣子”。 問題只是標簽在背景之外。
而且 Text 和 LabelText 不是垂直居中的。 另外一張照片:
我還嘗試使用填充(頂部和底部),但要么沒有改變任何東西,要么出現錯誤。
這是源代碼:
return TextField(
onChanged: (String? value) {
print(value);
onChanged(value);
},
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
prefixIcon: prefixIcon,
labelText: labelText,
labelStyle: TextStyle(
fontWeight: FontWeight.w700,
color: kInputColor,
fontSize: 14.0,
),
filled: true,
fillColor: kInputFillColor,
contentPadding: EdgeInsets.only(
top: 14.0,
bottom: 14.0,
left: 14.0,
right: 14.0,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(6.0),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(6.0),
),
),
cursorWidth: 1.5,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black,
fontSize: 14.0,
),
);
問題是我使用的邊框類型。 通過@Diwyansh 的回答,我發現TextField
使用的默認邊框是UnderlineInputBorder
。 我發現這種類型的邊框也具有設置borderRadius
和borderSide
的屬性。 因此,當我使用UnderlineInputBorder
而不是OutlineInputBorder
(對我來說這聽起來比UnderlineInputBorder
更有意義)時,標簽是在TextField
的背景中繪制的。 這是我的源代碼現在的樣子:
return TextField(
onChanged: (String? value) {
print(value);
onChanged(value);
},
decoration: InputDecoration(
prefixIcon: prefixIcon,
labelText: labelText,
labelStyle: TextStyle(
fontWeight: FontWeight.w700,
color: kInputColor,
fontSize: 14.0,
),
filled: true,
fillColor: kInputFillColor,
contentPadding: EdgeInsets.only(
top: 14.0,
bottom: 12.0,
left: 14.0,
right: 14.0,
),
border: UnderlineInputBorder(
borderRadius: BorderRadius.circular(6.0),
borderSide: BorderSide.none,
),
),
cursorWidth: 1.5,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black,
fontSize: 14.0,
),
);
根據 OutlineInputBorder 的官方 Flutter 文檔https://api.flutter.dev/flutter/material/OutlineInputBorder/OutlineInputBorder.html
InputDecoration.floatingLabelBehavior,當borderSide為BorderSide.none時應設置為FloatingLabelBehavior.never。 如果設為 FloatingLabelBehavior.auto,則標簽將延伸到容器之外,就好像邊框仍在繪制中一樣。
這意味着如果BorderSide
設置為BorderSide.none
,就像您所做的那樣,標簽在聚焦時會在背景容器之外。
所以你只需要將floatingLabelBehavior
設置為FloatingLabelBehavior.never
。 這將使它像hintText
一樣hintText
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.