在我的AppBar中,搜索输入为title
,清除按钮为actions
:
AppBar(
actions: <Widget>[IconButton(icon: Icon(Icons.clear), onPressed: () => queryController.clear())],
title: TextField(
autofocus: true,
controller: queryController,
decoration: InputDecoration(
hintText: 'Search...',
),
),
),
如何根据搜索字段的值动态显示清除按钮?
答案 0 :(得分:0)
只需在要动态隐藏的操作之前添加if (queryController.text.length > 0)
,然后将setState
添加到onChanged
的{{1}}方法中,这就是您的代码;
TextField
答案 1 :(得分:0)
在StatefulWidget
内,您可以使用setState和bool字段来跟踪操作是否显示:
bool _shouldHideAction;
TextEditingController _textEditingController;
@override
void initState() {
_shouldHideAction = true;
_textEditingController = TextEditingController();
super.initState();
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: _shouldHideAction ? [] : [Icon(Icons.clear)],
title: Text('appbarTitle'),
),
body: TextField(
style: TextStyle(color: Colors.red),
controller: _textEditingController,
onChanged: (newValue) {
if (newValue.length > 0) {
setState(() {
_shouldHideAction = false;
});
} else {
setState(() {
_shouldHideAction = true;
});
}
},
),
);
}