Flutter 文本字段清除按钮

问题描述 投票:0回答:1

我正在尝试构建一个带有清晰按钮的搜索字段,当我输入一些文本时,该按钮就会出现。但是我尝试使用三元条件来显示我的按钮,但它从未出现。

提前致谢

这是我的课:

`类 SearchField 扩展 StatefulWidget { @覆盖 _SearchFieldState createState() => _SearchFieldState(); }

类 _SearchFieldState 扩展状态 { TextEditingController _controller = TextEditingController();

@override
Widget build(BuildContext context) {
    return TextField(
        controller: _controller,
        style: const TextStyle(
            color: Colors.white,
        ),
        decoration: InputDecoration(
            labelText: 'Search',
            labelStyle: TextStyle(
                color: Color.fromARGB(255, 255, 255, 255).withOpacity(0.4),
                fontFamily: 'Inter',
            ),
            border: InputBorder.none,
            suffixIcon: _controller.text.isEmpty //my clear button
                            ? null
                            : IconButton(
                                    icon: Icon(Icons.clear),
                                    onPressed: () {
                                        setState(() {
                                            _controller.clear();
                                        });
                                    },
                                )
        ),
        onEditingComplete: () {
            // TODO: search contact with _controller.text
            FocusScope.of(context).unfocus();
        },
    );
}

}`

flutter button textfield ternary cleartext
1个回答
0
投票

提问后我就找到了答案:

我必须像这样在我的文本上添加 onChanged 并且它可以工作:

class SearchField extends StatefulWidget {
  @override
  _SearchFieldState createState() => _SearchFieldState();
}

class _SearchFieldState extends State<SearchField> {
  TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      style: const TextStyle(
        color: Colors.white,
      ),
      decoration: InputDecoration(
        labelText: 'Search',
        labelStyle: TextStyle(
          color: Color.fromARGB(255, 255, 255, 255).withOpacity(0.4),
          fontFamily: 'Inter',
        ),
        border: InputBorder.none,
        suffixIcon: _controller.text.isEmpty
            ? null
            : IconButton(
                icon: Icon(Icons.clear),
                onPressed: () {
                  setState(() {
                    _controller.clear();
                  });
                },
              ),
      ),
      onChanged: (text) {
        setState(() {
          // This will rebuild the widget and update the suffixIcon accordingly
        });
      },
      onEditingComplete: () {
        // TODO: search contact with _controller.text
        FocusScope.of(context).unfocus();
      },
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.