I am facing an issue in my Flutter app where I have a bottom sheet with a TextField. When the back button is pressed, I want to close the keyboard and unfocus the TextField. However, the TextField remains focused, even after the keyboard close. I have tried various solutions, including using WillPopScope, but none of them work as expected.
Infact, while textfield is open in bottomSheet, when the back button doesn’t do any actions. How can I properly close the keyboard and unfocus the TextField when the back button is pressed within the bottom sheet?
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) {
return StatefulBuilder(builder: (context, setModalState) {
return OnBackPressed(
perform: () {
print('The back button on the device was pressed');
_focusNode.unfocus();
},
child: Container(
// Bottom sheet content
child: TextField(
focusNode: _focusNode,
decoration: InputDecoration(
hintText: 'Add comments...',
),
textInputAction: TextInputAction.done,
onEditingComplete: () async {
_focusNode.unfocus();
// Additional logic after editing is complete
},
),
),
);
});
},
);
2
Answers
To Close keyboard programatically use FocusManager, it will close your keyboard and un-focus your textField.
Use like this:
check this gif:
To properly handle closing the keyboard and unfocusing the TextField when the back button is pressed within the bottom sheet, you can use a combination of the WillPopScope widget and managing the focus of the TextField. Here’s how you can modify your code:
In this code, I wrapped the bottom sheet content with a WillPopScope widget. The onWillPop callback is called when the back button is pressed. Inside this callback, I call _focusNode.unfocus() to close the keyboard and unfocus the TextField. Finally, I return true to allow the modal to be popped. This should properly handle the behavior you desire when the back button is pressed within the bottom sheet.