Created
April 28, 2023 14:25
-
-
Save rei-codes/2301df40242fe3a9369b214aa43e3579 to your computer and use it in GitHub Desktop.
Unfocus on tap outside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UnfocusArea extends StatelessWidget { | |
const UnfocusArea({super.key, required this.child}); | |
final Widget child; | |
@override | |
Widget build(BuildContext context) { | |
return GestureDetector( | |
// Makes clickable on everywhere even if the widget is not opaque | |
behavior: HitTestBehavior.opaque, | |
// Magic happens here | |
onTap: () => FocusScope.of(context).unfocus(), | |
child: child, | |
); | |
} | |
} | |
class UnfocusOnTapOutside extends StatelessWidget { | |
const UnfocusOnTapOutside({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
// Reusable widget for easier usage | |
return UnfocusArea( | |
child: Scaffold( | |
appBar: AppBar( | |
title: const Text('Unfocus on tap outside'), | |
), | |
body: const Center( | |
child: Padding( | |
padding: EdgeInsets.symmetric(horizontal: 16), | |
child: TextField( | |
decoration: InputDecoration(hintText: 'Click here to focus'), | |
), | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment