首页 > 解决方案 > 聚焦时 Flutter TextField 标签在背景之外

问题描述

标题应该说明一切。不过,这里有一些图片以便更好地理解。

它应该是什么样子(谷歌材料组件): 在此处输入图像描述

它实际上是什么样子的: 在此处输入图像描述

但是请忽略图片的底部边框“它应该是什么样子”。问题只是标签在背景之外。

而且 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,
  ),
);

标签: flutter

解决方案


根据 OutlineInputBorder 的官方 Flutter 文档 https://api.flutter.dev/flutter/material/OutlineInputBorder/OutlineInputBorder.html

InputDecoration.floatingLabelBehavior,当borderSide为BorderSide.none时,应设置为FloatingLabelBehavior.never。如果设为 FloatingLabelBehavior.auto,标签将延伸到容器之外,就好像仍在绘制边框一样。

这意味着如果BorderSide设置为BorderSide.none,就像您所做的那样,标签在聚焦时会看起来在背景容器之外。

所以你只需要设置floatingLabelBehaviorFloatingLabelBehavior.never. 这将使它像hintText


推荐阅读