How to clear in put text in Flutter

Viewed 48

I'm trying to clear the text when a user click on the X icon and my search result got empty when I click it but my input text is still there so I would be really appreciated if I can get any help or suggestion on how I can clear the inputed text too.

                  Expanded(
                      flex: 8,
                      child: GestureDetector(
                        onTap: () {},
                        child: TextFormField(
                          autofocus: true,
                          enabled: true,
                          onChanged: (va) {
                            filterSearchResult(va, model);
                          },
                          decoration: InputDecoration(
                              floatingLabelBehavior:
                                  FloatingLabelBehavior.never,
                              border: InputBorder.none,
                              hintStyle: TextStyle(
                                  color:
                                      Theme.of(context).secondaryHeaderColor)),
                        ),
                      )),
                  Expanded(
                    child: GestureDetector(
                        onTap: () {
                          setState(() {
                            items.clear();
                            itemList.clear();
                          });
                        },
                        child: Image.asset(
                          "assets/icons/cancel.png",
                          color: Theme.of(context).secondaryHeaderColor,
                          height: 30,
                        )),
                  ),
2 Answers

I use TextEditingController myController and set myController.text to null

You should use TextEditingController to clear the value of TextFormField.

// Some code ...

final textEditingController = TextEditingController();

// Some code ...

Expanded(
  flex: 8,
  child: GestureDetector(
    onTap: () {},
    child: TextFormField(
      autofocus: true,
      enabled: true,
      controller: textEditingController, // Your TextEditingController here
      onChanged: (va) {
        filterSearchResult(va, model);
      },
      decoration: InputDecoration(
        floatingLabelBehavior: FloatingLabelBehavior.never,
        border: InputBorder.none,
        hintStyle:
        TextStyle(color: Theme.of(context).secondaryHeaderColor),
      ),
    ),
  ),
),
Expanded(
  child: GestureDetector(
    onTap: () {
      setState(() {
        textEditingController.clear(); // Clear the TextFormField
        items.clear();
        itemList.clear();
      });
    },
    child: Image.asset(
      "assets/icons/cancel.png",
      color: Theme.of(context).secondaryHeaderColor,
      height: 30,
    ),
  ),
),
Related