簡體   English   中英

Flutter TextField 標簽在聚焦時位於背景之外

[英]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,
  ),
);

你可以得到它 InputDecoration 屬性

TextFormField(
      decoration: InputDecoration(
        labelText: "Label",
        filled: true),
    )

在此處輸入圖片說明

問題是我使用的邊框類型。 通過@Diwyansh 的回答,我發現TextField使用的默認邊框是UnderlineInputBorder 我發現這種類型的邊框也具有設置borderRadiusborderSide的屬性。 因此,當我使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM