how to track url in webview flutter

Viewed 32

I have a problem, it consists in the fact that I cannot track changes in the url in my webview page. I have an account where I make payments. This side does not change this is what "https://myUrl /uk /checkout/.........." looks like. The problem is that I cannot track the changes that occur in my webview page. My goal is to exit the page if my string is "https://myUrl/uk /success/.........." or "https://myUrl/uk/error/..... ..." Can anyone help me??

My code:

lass PayWebWidget extends StatefulWidget {
  final TransferDataFromOrderHistoryModul dateFromOrder;

  const PayWebWidget({
    super.key,
    required this.dateFromOrder,
  });

  @override
  PayWebWidgetState createState() => PayWebWidgetState();
}

class PayWebWidgetState extends State<PayWebWidget> {
  int _counter = 0;

  WebViewController? _controller;

  @override
  void initState() {
    super.initState();
    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  void _incrementCounter() {
    _controller!.goBack();
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: controller(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.arrow_back),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  _loadHtmlFromAssets( ) async {
    await _controller?.loadUrl('https://myUrl/api/3/checkout/.....');
  }


  WebView controller() {
    return WebView(
      // initialUrl: 'https://flutter.dev',
      gestureNavigationEnabled: true,
      debuggingEnabled: true,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate:(NavigationRequest request) {
      setState(() {
      });
      return NavigationDecision.prevent;
      },
    );
  }
}

1 Answers

You can track changes to url with navigationDelegate:

a small example:

WebView(
    initialUrl: yourInitialUrl,
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (WebViewController webViewController) {
      _controller.complete(webViewController);
    },
     navigationDelegate: (NavigationRequest request) {
          if (request.url == "https://myUrl/uk /success/.........." ||
              request.url == "https://myUrl/uk/error/..... ...") {
            //You can do anything ,the way you like

            //Prevent that url from loading and exit
            Navigator.pop(context);
          }
          //Any other url works
          return NavigationDecision.navigate;
        },
  )
Related