【问题标题】:Flutter TextField, how to use different style for label inside vs above the text fieldFlutter TextField,如何在文本字段内部与上方的标签中使用不同的样式
【发布时间】:2019-04-28 04:13:43
【问题描述】:

我有以下TextField:

TextField(
    decoration: InputDecoration(
        labelStyle: TextStyle(
            color: I_WANT_TO_CHANGE_THIS,
        ),
        labelText: widget.label,
    ),
);

如何更改颜色,使其在文本字段(提示)内时为灰色,而在文本字段上方(被聚焦)浮动时为黑色。

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    尝试使用FocusNode:

    class _MyHomePageState extends State<MyHomePage> {
    
      FocusNode _focusNode = FocusNode();
      Color color;
    
      @override
      Widget build(BuildContext context) {
    
        _focusNode.addListener(() {
          setState(() {
           color = _focusNode.hasFocus ? Colors.blue : Colors.red; 
          });
        });
    
        return Scaffold(
          body: Center(
            child: TextField(
              focusNode: _focusNode,
              decoration: InputDecoration(
                labelText: 'Label',
                labelStyle: TextStyle(
                  color: _focusNode.hasFocus ? Colors.blue : Colors.red,
                )
              ),
              autofocus: false,
            ),
          )
        );
      }
    }
    

    请注意,在此特定示例中,文本字段一旦被选中就会始终处于焦点位置,因为只有一个文本字段。

    【讨论】:

    • 我认为这里不需要color 变量和addListener
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2021-12-25
    • 2023-03-22
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多