I have a TextField
inside my Flutter app, and I want to unfocus it (dismiss the keyboard) when the user presses the back button
I am already using GestureDetector
to unfocus the TextField
when the user taps anywhere outside:
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
body: TextField(
controller: searchC,
decoration: InputDecoration(
labelText: "Search...",
suffixIcon: Icon(Icons.search),
),
),
),
);
Expected Behavior: When the user presses the back button, the keyboard should close (unfocus the TextField).
If the keyboard is already dismissed, then the back button should work as usual.
And I have a dialog, the issue is when i close the dialog it's auto-focus on this textfield
How can I fix this behavior ? check the video for better understanding
I appreciate any help.
I have a TextField
inside my Flutter app, and I want to unfocus it (dismiss the keyboard) when the user presses the back button
I am already using GestureDetector
to unfocus the TextField
when the user taps anywhere outside:
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
body: TextField(
controller: searchC,
decoration: InputDecoration(
labelText: "Search...",
suffixIcon: Icon(Icons.search),
),
),
),
);
Expected Behavior: When the user presses the back button, the keyboard should close (unfocus the TextField).
If the keyboard is already dismissed, then the back button should work as usual.
And I have a dialog, the issue is when i close the dialog it's auto-focus on this textfield
How can I fix this behavior ? check the video for better understanding https://drive.google/file/d/133Img3iGJIaiDddCayNVCIVM4av6TD-e/view?usp=sharing
I appreciate any help.
Share Improve this question asked Mar 16 at 19:38 Mamoon AnsariMamoon Ansari 411 bronze badge 2 |3 Answers
Reset to default 0used dispose method to disposed controller. In you code you are using
controller: searchC,
@override
void dispose() {
searchC.dispose();
// TODO: implement dispose
super.dispose();
}
when displaying dialog first unfocus the TextField and then display the dialog.
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
// Unfocus TextField
FocusManager.instance.primaryFocus?.unfocus();
// Show Dialog
showDialog(
context: context,
builder: (context) {
return YourDialogWidget();
},
);
},
label: const Text("Add Item"),
icon: const Icon(Icons.add),
)
U can remove focus immediately after closing the dialog like so
floatingActionButton: FloatingActionButton.extended(
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return YourDialogWidget();
},
);
FocusManager.instance.primaryFocus?.unfocus();
},
label: const Text("Add Item"),
icon: const Icon(Icons.add),
)
autofocus: false,
? so that when the widget initialized theTextField
is initially unfocused – Mahmoud Al-shehyby Commented Mar 16 at 22:10