Listen for url redirects in the flutter_webview

3 min read 05-10-2024
Listen for url redirects in the flutter_webview


Detecting URL Redirects in Flutter Webview: A Step-by-Step Guide

The Problem:

Imagine you're building a Flutter app that utilizes a webview to display external content. You need to know when the webview's URL changes due to a redirect, enabling you to handle specific actions or display relevant information to your users.

Rephrasing the Problem:

You want your Flutter app to be aware of URL redirects happening within a webview, allowing you to react accordingly. For example, you might want to show a loading indicator during a redirect or log the redirect URL for analytics.

Scenario & Code:

Let's say you have a simple Flutter app that displays a webview loading a specific URL:

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewScreen extends StatefulWidget {
  @override
  _WebviewScreenState createState() => _WebviewScreenState();
}

class _WebviewScreenState extends State<WebviewScreen> {
  final String _initialUrl = 'https://www.example.com';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Webview Example'),
      ),
      body: WebView(
        initialUrl: _initialUrl,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
        },
      ),
    );
  }
}

This code simply loads the specified URL in the webview. However, it doesn't provide a way to detect redirects.

Solution & Insights:

The webview_flutter package provides a solution through the onNavigationRequest callback. This callback is triggered whenever the webview navigates to a new URL, including redirects.

Code with URL Redirect Detection:

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewScreen extends StatefulWidget {
  @override
  _WebviewScreenState createState() => _WebviewScreenState();
}

class _WebviewScreenState extends State<WebviewScreen> {
  final String _initialUrl = 'https://www.example.com';
  late WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Webview Example'),
      ),
      body: WebView(
        initialUrl: _initialUrl,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
        },
        onNavigationRequest: (NavigationRequest request) {
          // Check if the request is a redirect
          if (request.isForMainFrame && request.url != _initialUrl) {
            print('Redirect detected! New URL: ${request.url}');
            // Handle the redirect, e.g., display a loading indicator
          }
          return NavigationDecision.navigate;
        },
      ),
    );
  }
}

Explanation:

  1. onNavigationRequest callback: This callback is called whenever the webview navigates to a new URL. It receives a NavigationRequest object containing information about the navigation.
  2. isForMainFrame: This property indicates whether the request is for the main frame of the webview. This helps distinguish between redirects and navigation within the webview's current page.
  3. request.url != _initialUrl: This condition checks if the requested URL is different from the initial URL. If it's different, it indicates a redirect.
  4. Handling the redirect: You can now perform actions based on the detected redirect, like displaying a loading indicator or logging the redirect URL.

Additional Value:

  • Advanced Redirects: For more complex cases involving multiple redirects, consider using a state variable to track the current URL and compare it with the previous URL in the onNavigationRequest callback.
  • Handling Redirects for Specific URLs: You can customize your logic to only detect and handle redirects for certain URLs.
  • Error Handling: Implement error handling mechanisms in case of issues with the webview or the redirect process.

Conclusion:

By leveraging the onNavigationRequest callback and carefully examining the NavigationRequest object, you can efficiently detect URL redirects within your Flutter webview and react accordingly. This empowers you to create more responsive and informative user experiences in your applications.

Resources: