Flutter 如何使用TextEditingController创建带有清除按钮的TextField?
我试图用clear button创建一个文本字段,但当我输入一些值时,并没有我想要的clear button显示。似乎无法检测到对Flutter 如何使用TextEditingController创建带有清除按钮的TextField?,flutter,dart,flutter-layout,Flutter,Dart,Flutter Layout,我试图用clear button创建一个文本字段,但当我输入一些值时,并没有我想要的clear button显示。似乎无法检测到对\u firstname controller.text的更改。我如何解决这个问题 class TextFieldWithClearBtn扩展StatefulWidget{ @凌驾 _TextFieldWithClearBtnState createState()=>\u TextFieldWithClearBtnState(); } 类_textfieldwith
\u firstname controller.text的更改。我如何解决这个问题
class TextFieldWithClearBtn扩展StatefulWidget{
@凌驾
_TextFieldWithClearBtnState createState()=>\u TextFieldWithClearBtnState();
}
类_textfieldwith clearbtnstate扩展状态{
最终TextEditingController _firstNameController=TextEditingController();
@凌驾
无效处置{
super.dispose();
_dispose();
}
@凌驾
小部件构建(构建上下文){
返回容器(
子项:TextFormField(
控制器:_firstname控制器,
装饰:输入装饰(
labelText:“名字”,
后缀:_firstNameController.text.isNotEmpty
?手势检测器(
onTap:(){
WidgetsBinding.instance.addPostFrameCallback((\u)=>\ u firstNameController.clear());
},
子:图标(Icons.clear,color:Colors.black38),
)
:null
),
),
);
}
}
而不是后缀
,而是后缀
。这样,如果textformfield
不在焦点位置,则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)
)
),
),
希望这有帮助。非常感谢你,达珊。这很有帮助!我已经想了好几个小时了!
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)
)
),
),