【问题标题】:How to I put an "X" to clear the search box in my Flutter TextField Widget?如何在 Flutter TextField Widget 中添加“X”以清除搜索框?
【发布时间】:2020-09-26 04:22:51
【问题描述】:

以下代码提供了用于搜索的 TextField,但是,我希望在右侧清除“X”,以便用户可以清除搜索而无需退格。

TextField(
            decoration: InputDecoration(
                contentPadding: EdgeInsets.all(16.0),
                prefixIcon: Icon(
                  Icons.search,
                  color: Colors.white,
                ),
                //Placeholder potential X for clearing search
                /*suffix: IconButton(
                    icon: Icon(Icons.clear), onPressed: () => TODO),*/
                hintText: 'Search by name',
                hintStyle: TextStyle(
                    fontWeight: FontWeight.w500, color: Colors.white)),
            onChanged: (string) {
              setState(() {
                filterAssets = assets
                    .where((test) => (test.name
                        .toLowerCase()
                        .contains(string.toLowerCase())))
                    .toList();
              });
            },
          ),

【问题讨论】:

    标签: flutter widget textfield


    【解决方案1】:

    给它一个textController..

    还有onPressed你可以清除它..

    
    TextField(
                controller: textController,
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(16.0),
                    prefixIcon: Icon(
                      Icons.search,
                      color: Colors.white,
                    ),
                    //Placeholder potential X for clearing search
                    suffix: IconButton(
                        icon: Icon(Icons.clear), onPressed: () => textController.clear()),
                    hintText: 'Search by name',
                    hintStyle: TextStyle(
                        fontWeight: FontWeight.w500, color: Colors.white)),
                onChanged: (string) {
                  setState(() {
                    filterAssets = assets
                        .where((test) => (test.name
                            .toLowerCase()
                            .contains(string.toLowerCase())))
                        .toList();
                  });
                },
              ),
    
    

    希望它能解决你的问题..

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多