如何在焦点上更改TextField的textLable颜色

时间:2019-05-17 13:31:53

标签: flutter flutter-layout

我应该在代码中添加些什么以实现TextField的textLable颜色为绿色(聚焦)。

 TextField(
  keyboardType: TextInputType.emailAddress,
  cursorColor: CustomColors.seaweed,
  keyboardAppearance: Brightness.light,
  autocorrect: false,
  style: TextStyle(
      color: Colors.black
  ),
  decoration: InputDecoration(
    fillColor: CustomColors.seaweed,
    hasFloatingPlaceholder: true,
    labelText: "Email",
    hintText: "Please enter email",
    focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: CustomColors.seaweed)
    ),

  ),

)

enter image description here

1 个答案:

答案 0 :(得分:2)

创建一个FocusNode并为其添加一个侦听器。聚焦后,将标签颜色更改为绿色。

class Foo extends StatefulWidget {
  @override
  createState() => _FooState();
}

class _FooState extends State<Foo> {
  final FocusNode focusNode = FocusNode();

  TextStyle labelStyle;

  @override
  void initState() {
    super.initState();
    focusNode.addListener(onFocusChange);
  }

  void onFocusChange() {
    setState(() {
      labelStyle = focusNode.hasFocus ? TextStyle(color: Colors.green) : null;
    });
  }

  @override
  void dispose() {
    focusNode.removeListener(onFocusChange);
    super.dispose();
  }

  ...

  TextField buildTextField() {
    return TextField(
      focusNode: focusNode,
      decoration: InputDecoration(
        labelStyle: labelStyle,
        ...
      ),
      ...
    );
  }
}