Flutter Webview Dismiss Keyboard

1.1k Views Asked by At

I am sending users to a payment form via a Flutter WebView. At the end, after payment is received, my Flutter app is receiving a message that informs me that the purchase is completed. The view that is displayed at this point is the order summary/receipt. The user won't always dismiss the keyboard after filling out the payment form. I am having troubles getting the keyboard to dismiss automatically for them.

I have only tested on Android emulator and device. The keyboard does not dismiss for either.

When the order completed message is received, I am setting the state of the orderCompleted variable to true which triggers a rebuild and when true it calls FocusScope.of(context).unfocus(); to attempt to dismiss the keyboard. This is not working. I've also called this code inside of the MobileOrderReceived receiver function and it doesn't work there either.

Any thoughts on what I could do to solve the issue?

Here is my build function as it is right now:

bool orderCompleted = false;

@override
Widget build(BuildContext context) {
    if (orderCompleted) {
        FocusScope.of(context).unfocus(); // hides the keyboard when the order is received as successful  
    }
    Set<JavascriptChannel> jsChannels = new Set<JavascriptChannel>();
    jsChannels.add(
        JavascriptChannel(
            name: "MobileOrderReceived",
            onMessageReceived: (JavascriptMessage receiver) async { 
                print("Order Completed => ${receiver.message}");
                // { ... } code for saving to order history
                setState(() {
                    orderCompleted = true;
                });
            }
        )
    );
    return Scaffold(
        appBar: appBar(context),
        body: mainContainer(
            WebView(
                initialUrl: widget.url, 
                debuggingEnabled: true,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: jsChannels,
                onWebResourceError: (error) {
                    print("==> Web Resource Error <==");
                    print(error);
                },
            )
        ),
        drawer: MainMenu.buildMenu(context),
    );
}
2

There are 2 best solutions below

2
On

One option would be to use FocusManager, more specifically:

FocusManager.instance.primaryFocus.unfocus();
0
On

Found some workaround and it is working:

webViewController.runJavaScript("(document.activeElement).blur()");

reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur