Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Dismiss the keyboard before opening a modal

An open keyboard takes a huge portion of the screen. To reclaim that space, always aim to close the keyboard when a user is done typing.

Look at the video below: the user taps the "Note" field, types something, then taps the "City" field which opens a custom modal. Although the keyboard seems to be closed when the modal opens, closing it reopens the keyboard and focuses the "Note" field again:

But the user was done typing: they moved to another field.

To fix this side effect, call FocusManager.instance.primaryFocus?.unfocus(); before opening a modal:

CustomDropdown(
    title: 'City',
    value: selectedCity,
    onTap: () async {
        // Add this before opening modal
        FocusManager.instance.primaryFocus?.unfocus();
  
        // Open picker, update state etc.
    },
)

Now, much smoother:

Don't use FocusScope: FocusScope.of(context) looks for the nearest "focus" in the widget tree. FocusManager holds the latest focused one. Use that.

Also read: Dismiss the keyboard when users scroll a form

Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me