【问题标题】:How to create TextField with Clear button using TextEditingController?如何使用 TextEditingController 创建带有清除按钮的 TextField?
【发布时间】:2020-08-15 00:13:09
【问题描述】:

我尝试创建一个带有清除按钮的 TextField,但是当我输入一些值时,没有显示我想要的清除按钮。似乎它无法检测到_firstNameController.text 的更改。我该如何解决这个问题?

class TextFieldWithClearBtn extends StatefulWidget {
  @override
  _TextFieldWithClearBtnState createState() => _TextFieldWithClearBtnState();
}

class _TextFieldWithClearBtnState extends State<TextFieldWithClearBtn> {
  final TextEditingController _firstNameController = TextEditingController();

  @override
  void dispose {
    super.dispose();
    _firstNameController.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextFormField(
        controller: _firstNameController,
        decoration: InputDecoration(
          labelText: "First name",
          suffixIcon: _firstNameController.text.isNotEmpty
            ? GestureDetector(
              onTap: () {
                WidgetsBinding.instance.addPostFrameCallback((_) => _firstNameController.clear());
              },
              child: Icon(Icons.clear, color: Colors.black38),
            )
            : null
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart flutter-layout


    【解决方案1】:

    你不是suffixIcon,而是suffix。这样,如果textformfield 不在焦点上,clear 按钮将不可见,并且当您点击该字段时将显示icon。此外,当您在输入内容后点击clear 图标时,它会清除该字段。下面的工作示例代码:

    TextFormField(
          controller: _firstNameController,
                          textAlign: TextAlign.left,
                          cursorColor: Colors.white,
                          onChanged: (value) {
    
                          },
                          style: TextStyle(color: Colors.white),
                          decoration: InputDecoration(    
                            labelText: 'First Name',
                            suffix: GestureDetector(
                            onTap: () {
                              _firstNameController.clear();
                            },
                              child: Icon(Icons.clear)
                            )
                          ),
                        ),
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢达山。这很有帮助!我已经想了好几个小时了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-09-19
    • 1970-01-01
    • 2019-11-20
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多