Flutter – Respecting the Softkeyboard Insets
Flutter has made it simpler and easier to make a beautiful and interactive user interface. But there comes a problem faced by many flutter developers while working with soft keyboard inputs in the lower portion of the screen. The problem is whenever a user attempts to fill an input form (whose parent widget is a Card, Container, or something similar) in the lower part of the screen, the soft-keyboard tends to cover that form. The same problem will be replicated below and will show a simple solution to this problem.
Here, in the app below you can see that whenever the user tries to fill the input form the soft keyboard covers the form and the user can’t move to another line without going back from the keyboard.
Below is the code of the part which needs to be improved. It mainly contains the input form and some functions to handle the input. If we look at the widget tree of the input form we can see that the parent widget which composed the form is just a simple Card, which further contains two TextFields, a Container with date selection, and a RaisedButton.
The solution that we want to achieve is whenever a user taps on the TextFiled and the keyboard comes out the input form should also move up with a height equivalent to the keyboard’s and the form should be scrollable for easy access. This can be achieved in the following steps:
- Replacing the EdgeInsets.all with EdgeInsets.only in the padding of the Card widget. This will give us control over the individual padding.
- In the bottom argument of the padding, we will use MediaQuery (MediaQuery.of(context).viewInsets.bottom) to know the height of the keyboard and add it to the bottom padding. This way we whenever the keyboard will appear the form will move up with the height equivalent to that of the keyboard.
- At last, we will wrap the entire input form with SingleChildScrollView, to make it scrollable. It will make switching to the next input field easier.
This is how the input form will behave after the correction. The input form moves up in accordance with the height of the soft-keyboard, which makes all the fields visible. And in addition to that, the form is also scrollable now.