Is there a way to autofocus keyboard in webview textinput field in flutter?

1.7k views Asked by At

I am using InAppWebView to show the webpage in a flutter app. Here keyboard is shown only when I tap on the input field. Is there a way that the keyboard is visible before tapping on the input field? The keyboard should appear right after navigating to this screen. Here is the code:

import 'package:flutter_inappwebview/flutter_inappwebview.dart';


class WebViewScreen extends StatefulWidget {
  const WebViewScreen({Key? key}) : super(key: key);

  @override
  State<WebViewScreen> createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: InAppWebView(
            initialUrlRequest:
                URLRequest(url: Uri.parse('https://www.google.com')),
            onWebViewCreated: (InAppWebViewController controller) {
              print('onWebViewCreated');
            },
            onProgressChanged:
                (InAppWebViewController controller, int progress) {
              print('onProgressChanged: $progress');
            },
          ),
        ),
      ),
    );
  }
}

enter image description here enter image description here

1

There are 1 answers

1
Pathik Patel On

Using addUserScript method gives method implementation error.

And using webview_flutter plugin, it works:

class WebViewPage extends StatelessWidget {
  const WebViewPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WebView(
      javascriptMode: JavascriptMode.unrestricted,
      initialUrl: "https://google.com",
      onWebViewCreated: (webViewController) {
        String jsStr = "window.addEventListener('load', (event) => {"
            "let i = document.getElementsByTagName('input');"
            "i[0].focus();"
            "console.log('done');"
            "});";
        webViewController.runJavascript(jsStr);
      },
    );
  }
}