How to initiate WebViewController in flutter

1,372

From the docs of WebViewController, you can see that it says,

A WebViewController instance can be obtained by setting the WebView.onWebViewCreated callback for a WebView widget.

Now if we check the docs for onWebViewCreated, we see that it is of type WebViewCreatedCallback, which provides an instance of WebViewController as it's parameter in the callback you provide.

So, first

// Make it late since we can't create an instance by ourselves
late WebViewController _webViewController;

Then, in your build method where you are using the widget,

WebView(
  onWebViewCreated: (controller) {
    // We are getting an instance of the controller in the callback
    // So we take it assign it our late variable value
    _webViewController = controller,
  },
  .....

Now, you can use your _webViewController anywhere in your code.

Share:
1,372
the-a-monir
Author by

the-a-monir

Updated on December 30, 2022

Comments

  • the-a-monir
    the-a-monir over 1 year

    I was trying to declare a variable in class level as below:

    WebViewController _webViewController = WebViewController();

    sothat I can reuse that in other functions.But for nullsafety issue I tried to initialize it, but showing doesn’t have a default constructor.I tried also like,

     WebViewController _webViewController ; (it shows to add late modifier)
    

    or

    WebViewController _webViewController = null; (null can not be assigned)
    

    how should I declare ?

    • Nisanth Reddy
      Nisanth Reddy about 3 years
      This depends on the package that you are using. Which one are u using ?
    • the-a-monir
      the-a-monir about 3 years
      'package:webview_flutter/webview_flutter.dart'; (webview_flutter: ^1.0.0)
  • ezaspi
    ezaspi about 2 years
    This does not seem to be true. I get the error "has not been initialized" if I try to use it in init.
  • Nisanth Reddy
    Nisanth Reddy about 2 years
    Hi, which init are you talking about ? Also since we only get a instance of the controller one the webview is ready, you should have a nullable type for the controller variable. From your error, it might be that you are just accessing it even before the webview has been created.