Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unfocus text field in flutter?

enter image description here

I don't know if this is normal flutter behavior, but it is annoying that you lose focus only when you tap on the keyboard "ok" button to lose focus. If this is not done, the cursor will remain active within the text field.

What is the best practice to avoid this? (In the gif it is not well appreciated, but the only way to lose focus is by tapping on the "ok" button on the keyboard, otherwise the cursor will always be active regardless of whether you tap on other areas of the screen)

    Widget _searchBar() {
     return Container(
      child: TextField(
        textAlignVertical: TextAlignVertical.center,
        style: TextStyle(
          textBaseline: TextBaseline.alphabetic,
          color: _styles["gris_oscuro1"]["color"],
        ),
        onChanged: (value) {},
        decoration: InputDecoration(
          filled: true,
          fillColor: _styles["gris_claro"]["color"],
          alignLabelWithHint: true,
          hintText: "Buscar por código",
          hintStyle: TextStyle(color: _styles["gris_oscuro2"]["color"]),
          prefixIcon:
              Icon(Icons.search, color: _styles["gris_oscuro2"]["color"]),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(40)),
            borderSide:
                BorderSide(color: _styles["gris_claro"]["color"], width: 1.0),
          ),
        ),
      ),
    );
    );


    Scaffold(
        key: _scaffoldKey,
        backgroundColor: _styles["fondo"]["bg"],
        drawer: MenuWidget(),
        body: SafeArea(
        child: _searchBar(),
        )
like image 823
yavg Avatar asked Oct 29 '25 09:10

yavg


1 Answers

enter image description here

Wrap your full page in GestureDetector and modify it's onTap function as follows:

@override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () { //here
        FocusScope.of(context).unfocus();
        new TextEditingController().clear();
      },
      child: Container(
      ...
    );
  }
like image 117
Yudhishthir Singh Avatar answered Oct 31 '25 01:10

Yudhishthir Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!