首页 > 解决方案 > 聚焦时对齐TextField的labelText

问题描述

labelText 属性 https://api.flutter.dev/flutter/material/InputDecoration/labelText.html 当文本字段被聚焦并且你有这样的 Inputdecoration 时向上移动:

InputDecoration(
  labelText: labelText,
  filled: true,
  enabledBorder: OutlineInputBorder(
    borderSide: const BorderSide(
      color: ImpexColors.grey,
      width: 1.0,
    ),
  ),
  focusedBorder: OutlineInputBorder(
    borderSide: const BorderSide(
      color: ImpexColors.secondaryColor,
      width: 2.0,
    ),
  ),
  labelStyle: TextStyle(
    color: ImpexColors.blue,
  ),
)

然后在上边框的中间对齐。当 TextField 聚焦时,是否有可能改变 labelText 的位置?

标签: fluttertextfield

解决方案


有可能吗,基达?

  FocusNode myFocusNode = FocusNode();
  ...
  TextFormField(
      focusNode: myFocusNode,
      decoration: InputDecoration(
        labelStyle: TextStyle(
          height: myFocusNode.hasFocus ? 0.1 : 1, // 0,1 - label will sit on top of border
        ),
        labelText: labelText,
  ...
      ));

还必须添加:

onTap: () =>  setState(() {FocusScope.of(context).requestFocus(myFocusNode);})

推荐阅读