How to Get Current URL in Flutter Web App
In this article
To get the current URL in a Flutter web app, use the url_strategy package (specifically path_url_strategy) combined with the navigator_key.currentContext and RouterConfig from the flutter_web_plugins library. This approach allows you to read the browser's address bar directly within your widget tree, enabling dynamic content loading based on routes or query parameters.
What You'll Need
- A Flutter project configured for web support (run
flutter create .if needed). - The
url_strategypackage added to yourpubspec.yaml. - Basic understanding of Flutter's navigation system and widgets.
- An IDE like VS Code or Android Studio with the Flutter extension installed.
Step-by-Step
- Add the Dependency: Open your
pubspec.yamlfile and addurl_strategy: ^0.3.0under thedependenciessection. Runflutter pub getto install it. This package is essential because Flutter’s default routing uses hash-based URLs (e.g.,#/home), which are often undesirable for SEO and clean URLs. Switching to path-based strategy makes the URL look like standard web paths (/home). - Initialize the Strategy: In your
main.dartfile, before callingrunApp(), you must set the URL strategy. Add the following line:setPathUrlStrategy();. This ensures that when the app loads, it interprets the browser's path correctly without the hash symbol. Note that this function must be called synchronously before the framework initializes. - Create a Global Navigator Key: To access the current route information from anywhere in your app, define a global key. At the top of your
main.dartor a dedicated navigation service file, declare:final GlobalKey. This key will be passed to yournavigatorKey = GlobalKey (); MaterialApporCupertinoAppvia thenavigatorKeyproperty. - Access the Current URL: Inside any widget where you need the URL, you can retrieve the current location using the
routerAPI. The most reliable method in modern Flutter versions involves accessing theRouterConfigassociated with the navigator state. For example, in aStatefulWidget, you might use:final uri = RouterConfig.of(context)?.uri;
If you are using a custom router setup, ensure you have access to the context. Alternatively, a simpler method for basic path reading is:final uri = Uri.parse(navigatorKey.currentContext?.findAncestorWidgetOfExactType()?.runtimeType.toString() ?? '');
However, the cleanest approach is to use thego_routerpackage if you are doing complex routing, which providesGoRouterStatewith a directuriproperty. If sticking to standard Flutter navigation, you can extract the path from theRouteInformationParser. - Parse Query Parameters: Once you have the
Uriobject, you can easily extract query parameters. Useuri.queryParameters['key']to get specific values. For example, if the URL is/profile?id=123,uri.queryParameters['id']will return'123'. This is crucial for dynamic pages like user profiles or search results. - Handle Initial Route: Ensure your app handles the initial route correctly. When the page is refreshed, Flutter needs to know what to load. Configure your
MaterialAppwith anonGenerateInitialRoutescallback or use aRouteInformationParserthat respects the initial URI provided by the browser. This prevents the app from always landing on the home screen upon refresh.
Common Mistakes
One frequent error is forgetting to call setPathUrlStrategy() before runApp(). This leads to hash-based URLs, breaking any logic expecting clean paths. Another mistake is trying to access the navigator context in initState of a widget that isn't yet mounted; always check if the context is valid or use WidgetsBinding.instance.addPostFrameCallback to defer the URL reading until after the first frame is built. Additionally, developers often confuse the location string with the full Uri; remember that location only gives the path, while uri gives the complete structure including host and query params.
Tips
Consider using the go_router package for production apps. It simplifies deep linking, nested navigation, and URL parsing significantly compared to raw Flutter navigation. If you must stick to standard navigation, wrap your URL-reading logic in a utility class to keep your widgets clean. Always handle cases where the URL might be null or malformed, especially during rapid navigation transitions. For SEO purposes, ensure your server is configured to serve index.html for all routes (SPA fallback) so that direct links to sub-pages don't result in 404 errors.
Troubleshooting
If the URL returns empty or incorrect, first verify that setPathUrlStrategy() was called correctly. Check the browser console for JavaScript errors related to history manipulation. If using go_router, ensure your routeInformationProvider is properly linked to the router. Restart the development server and clear the browser cache, as cached scripts can sometimes interfere with new routing configurations. If the app crashes on reload, ensure your server is configured to redirect all non-static file requests to index.html. For local testing, you can use tools like http-server or live-server to simulate proper SPA behavior.
Frequently Asked Questions
Can I get the URL without adding external packages?
Yes, but it requires more boilerplate code using the internal flutter_web_plugins library. Using url_strategy is recommended for simplicity and reliability.
Why does my URL have a hash (#) in it?
This happens if you haven't called setPathUrlStrategy() in main.dart. Flutter defaults to hash-based routing for compatibility; switching to path strategy removes the hash.
How do I read query parameters like ?id=5?
Once you have the Uri object from the router, use uri.queryParameters['id']. This returns a string value for the specified key.
Does this work for mobile apps too?
No, url_strategy and browser-specific URL APIs only apply to the web target. Mobile apps use native navigation stacks and do not expose browser URLs in the same way.
What if the URL changes but my widget doesn't update?
You need to listen to route changes. In standard Flutter, this involves using a RouteObserver or rebuilding widgets based on RouterConfig updates. With go_router, use the GoRouter.refreshListenable to trigger rebuilds.
Is it safe to use this for authentication tokens?
Be cautious. Storing sensitive tokens in URL query parameters exposes them in browser history and server logs. Prefer storing tokens in secure cookies or local storage instead.