简体   繁体   中英

Flutter Webview Dismiss Keyboard

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),
    );
}
FocusScope.of(context).requestFocus(FocusNode());

This line is working for me to close the keyboard programetically.

One option would be to useFocusManager , more specifically:

FocusManager.instance.primaryFocus.unfocus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM