Flutter Web/iOS: Handling soft keyboard behavior

Abrar Malekji
Mindful Engineering
2 min readNov 12, 2021
Photo by Jay Zhang on Unsplash

In this article, we will see how to handle the keyboard done button behavior on the ios, There are some issues on the ios when interacting with the keyboard,e.g In chrome when the done button is clicked, the keyboard does not hide, and In Safari, the done button only hides the keyboard but does not remove focus.

Because chrome and safari have different issues, first we have to detect if the device is ios and on which browser it is?. To achieve that, try this.

class DeviceInfo {static bool isChromeInIOS() {return isIOS() && !isSafari();}static bool isSafari() {if(window.navigator.userAgent.toString().toLowerCase().contains(‘crios’)) {return false;}return js.context.callMethod(‘isSafari’, []);}static String getOSInsideWeb() {final userAgent = window.navigator.userAgent.toString().toLowerCase();if (userAgent.contains(‘iphone’)) return ‘ios’;if (userAgent.contains(‘ipad’)) return ‘ios’;if (userAgent.contains(‘android’)) return ‘Android’;return ‘Web’;}static int? get iosVersion {if(!isIOS()) {return null;}final agent=userAgent;final versionPart=agent.split(‘version/’)[1];return int.tryParse(versionPart.substring(0,versionPart.indexOf(‘.’)))??-1;}static bool isIOS() {return getOSInsideWeb() == ‘ios’;}}

once we get to know the device is ios, we have to check if a browser is chrome or safari.

Safari

When the done button is clicked in the Safari browser, the keyboard hides, but it does not remove focus from TextField, So then when we click outside of TextField keyboard pops up again, unfortunately, we don’t have any listener of this event, but there is one workaround!!

Clicking the done button fires event of type focusout, so we can add listener of this event,

if (DeviceInfo.isSafari() && DeviceInfo.isIOS()) {html.window.addEventListener(‘focusout’, removeFocus);}

So every time Safari fires focusout event, removeFocus method will be called.

Chrome

In chrome, the done button does not work at all, so we need to add another done button to hide the keyboard. To achieve that, we can use keyboard_actions package. what does it do? basically, it adds an action layer on the top of the keyboard action layer.

--

--

Abrar Malekji
Mindful Engineering

I am Software developer with experience in Android, Flutter and Django