Flutter:如何在AppBar中动态隐藏动作?

时间:2020-04-20 23:04:03

标签: flutter

在我的AppBar中,搜索输入为title,清除按钮为actions

AppBar(
        actions: <Widget>[IconButton(icon: Icon(Icons.clear), onPressed: () => queryController.clear())],
        title: TextField(
          autofocus: true,
          controller: queryController,
          decoration: InputDecoration(
            hintText: 'Search...',
          ),
        ),
      ),

如何根据搜索字段的值动态显示清除按钮?

2 个答案:

答案 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;
            });
          }
        },
      ),
    );
  }