Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: webview_flutter update url in same webview widget

Hey I am trying to create a screen which shows a webview with a bottomappbar. So you load the webview and when tapping on a item in the bottomappbar a other website should loaded in the same webview...

I cant figure out how to open another website other than I originaly parsed. I tried to update the url by using «setState» but it only updates the appbar title and the webview still shows the original website

Here is my current code:

class _WebviewContainer extends State<WebviewContainer> {
var url;
final key = UniqueKey();

_WebviewContainer(this.url); 

@override
Widget build(BuildContext context) {    
return Scaffold(
  appBar: AppBar(
    title: Text(url),
    actions: <Widget>[
      IconButton(
        icon: Icon(
          Icons.home,
          size: 40.0,
          color: Colors.white,
        ),
        onPressed: () => {
          //-> Here I set the new url but the webview always shows the origin website

          setState(() {
            url = 'https://stackoverflow.com/';
          })
        },
      )
    ],
  ),
  body: Column(
    children: <Widget>[
      Expanded(
        child: WebView(
          key: key,
          javascriptMode: JavascriptMode.unrestricted,
          initialUrl: url,              
        ),
      ),          
    ],
  ),
);
}
}

I took the code from a tutorial on YouTube and the creator also stated that the webview will reload if the state of the url changes, but unfortunately he did not show how to do it

If anybody could help me out?

Thanks in advance Doobie

like image 300
DoobieAsDave Avatar asked Mar 19 '19 16:03

DoobieAsDave


1 Answers

So I had a similar situation except i wanted a new url to be loaded in my webview when i selected an item from a dropdownmenu. How I did this was create an instance of WebViewController

WebViewController controller;

Then set this controller when the webview is created with the onWebViewCreated parameter

child: WebView(
      key: _key,
      javascriptMode: JavascriptMode.unrestricted,
      initialUrl: url,
    onWebViewCreated: (WebViewController webViewController) {
    controller = webViewController;}

Now you have the controller set, you can use its loadUrl method in setState() to change the displayed Url

setState(() {                
            controller.loadUrl(newUrl_here);

I just started with Flutter so could be a better way of course but this worked for me

like image 183
nyorn Avatar answered Oct 01 '22 17:10

nyorn