flutter
Dismiss the mobile screen keyboard in Flutter
The mobile screen keyboard is necessary for many users who need to type on their phone or tablet. However, there are times when the keyboard is just in the way and needs to be dismissed. This can be accomplished in Flutter by using the FocusManager.
ElevatedButton(
onPressed: () {
// This code will hide the mobile keyboard screen
FocusManager.instance.primaryFocus?.unfocus();
},
child: const Text('Hide Keyboard'),
)
The above code can be used if you are using Flutter version 2 or above. It is written with null safety that will dismiss the keyboard when executed on mobile devices.
We have created a textbox and a button where the keyboard screen will be seen on focus and when you click on the 'hide keyboard' button the keyboard screen will hide.
The code that can be used to hide the keyboard screen is as below.
FocusManager.instance.primaryFocus?.unfocus();
Full code example
Column(
children: [
const TextField(
autofocus: true,
),
ElevatedButton(
onPressed: () {
FocusManager.instance.primaryFocus?.unfocus();
},
child: const Text('Hide Keyboard'),
)
],
)
Explanation:
- The code example above creates a Column widget with two children: a TextField widget and an ElevatedButton widget.
- The TextField widget is configured to be autofocused, meaning that it will receive focus when the Column widget is first rendered.
- The ElevatedButton widget is configured with an onPressed callback that will be called when the button is tapped.
- This callback uses the FocusManager to unfocus the primary focus, which will hide the keyboard.
Was this helpful?
Similar Posts