How to initiate WebViewController in flutter

Issue

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 ?

Solution

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.

Answered By – Nisanth Reddy

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.