Search code examples
flutterflutter-layout

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(),
        )

Solution

  • 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(
          ...
        );
      }