'Detect a tap outside of a TextField to unfocus
I want to hide the keyboard when the user taps outside of a TextField. My current solution is to listen to taps in a GestureDetector that wraps the screen and call FocusScope.of(context).unfocus() to hide the keyboard.
The problem is that the GestureDetector doesn't detect taps on widgets like buttons. So when a button is tapped, the keyboard doesn't hide.
Solution 1:[1]
Since Button widgets handles their own gesture, you can just add FocusScope.of(context).unfocus() on your buttons' onPressed()
ElevatedButton(
onPressed: () {
// Unfocus from any focused TextField
FocusScope.of(context).unfocus();
// Do button function
},
child: Text('...'),
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omatt |
