Search code examples
flutterfocus

Flutter TextField: how to lose focus on tap outside?


Flutter TextField: how to lose focus on tap outside?

TextField()

It loses focus only when tap another widget that can take focus such as TextField.

What if the TextField is the only one widget in the page?


Solution

  • In TextField Widget class there is an argument called as onTapOutside, this method will call when-ever you tap outside the TextField, so you can do your code to un-focus or loose focus. For example:

    class CustomTextField extends StatelessWidget {
      const CustomTextField({super.key});
    
      @override
      Widget build(BuildContext context) {
        return TextField(
          // this method will call when you tap outside the TextField
          onTapOutside: (event) {
            // code to unfocus after tap outside
            FocusScope.of(context).unfocus();
          },
        );
      }
    }