I’m working on a Flutter app for the web, and I need to retrieve the current URL from a WebView. Specifically, I want to get the URL of the page that is being displayed in the WebView at any given time.
Is there a way to achieve this for the web platform in Flutter? I would appreciate any insights or recommendations on how to retrieve the current URL from a WebView, including any methods or techniques that might be helpful.
I tried several packages like webview_flutter_web: ^0.2.3+4 and easy_web_view: ^2.1.0,
none of them seem to meet my requirements.
Samir is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
To retrieve the current URL from a WebView in Flutter for the web platform, you can use the webviewx
package, which provides more flexibility for web-based applications.
solution
import 'package:flutter/material.dart';
import 'package:webviewx/webviewx.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: WebViewExample(),
);
}
}
class WebViewExample extends StatefulWidget {
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late WebViewXController webviewController;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("WebView URL Example"),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () async {
// Retrieve the current URL
final currentUrl = await webviewController.currentUrl;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Current URL: $currentUrl")),
);
},
),
],
),
body: WebViewX(
initialContent: 'https://flutter.dev',
initialSourceType: SourceType.url,
onWebViewCreated: (controller) {
webviewController = controller;
},
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
),
);
}
}
Just as simple as
final currentUrl = await webviewController.currentUrl;