2 years ago

#59597

test-img

imgingerbear

How to add parameters to the redirect url in Flutter webview?

I created this WebviewScaffoldScreen widget to load urls in my app. Whenever url is redirected, I would need to add certain ids and tokens to the redirected url so the server would accept this request and return the webpage that I need.

Redirected url:

"https://stack.com/messages/?id=1"

Url that I would like to achieve, then reload:

"https://stack.com/mesages/?id=1&user_id=333token=abc"

Is it possible to append/edit the redirect url in the navigation request? I tried to use webview controller and reloadUrl() with the appended url but it created a loop and the webview wasn't redirected to the appended url.

I'm using the package webview_flutter 3.0.0 in Flutter v2.8.0. Thanks a lot!

class WebviewScaffoldScreen extends StatefulWidget {
  @required
  final String url;
  final String appBarTitle;
  final bool? withJavascript;

  const WebviewScaffoldScreen({
    required this.url,
    required this.appBarTitle,
    this.withJavascript,
    Key? key,
  }) : super(key: key);

  @override
  State<WebviewScaffoldScreen> createState() => _WebviewScaffoldScreenState();
}

class _WebviewScaffoldScreenState extends 
State<WebviewScaffoldScreen> {
  late final WebViewController webViewController;
  final userId = "333";
  final token = "abc";

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text(widget.appBarTitle)),
      body: WebView(
        initialUrl: widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webController) {
          webViewController = webController;
        },
        navigationDelegate: (NavigationRequest request) {
          
          if (request.url.contains('callback:close')) {
            Navigator.of(context).pop();
            return NavigationDecision.prevent;
          }

          if (request.url.contains('messages')) {
            // I was tring to use webviewController to reload the url, but this creates a loop that kept reloading the webview :(

            String updatedUrl = request.url + "&" + "user_id=$userId&" + "token=$token&";
            webViewController.loadUrl(updatedUrl);
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    );
  }
}

flutter

url

webview

webview-flutter

0 Answers

Your Answer

Accepted video resources