Adding Back and Forward Buttons in Flutter WebView

Flutter

Navigating web pages inside a Flutter app isn’t complete without giving users the ability to move back and forth—just like in a regular browser. In this article, we’ll explore how to implement back and forward navigation buttons when using WebView in Flutter.

1. Setup: webview_flutter + WebViewController

To manage WebView navigation, you’ll use WebViewController. Make sure you’ve already added the webview_flutter package to your project:

dependencies:
  webview_flutter: ^4.2.2

2. Full Example: WebView with Navigation Buttons

Here’s a complete widget that displays a WebView with back and forward buttons at the bottom:

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

class WebViewWithControls extends StatefulWidget {
  @override
  _WebViewWithControlsState createState() => _WebViewWithControlsState();
}

class _WebViewWithControlsState extends State<WebViewWithControls> {
  late final WebViewController _controller;
  bool _canGoBack = false;
  bool _canGoForward = false;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('https://example.com'))
      ..setNavigationDelegate(NavigationDelegate(
        onPageFinished: (_) async {
          final back = await _controller.canGoBack();
          final forward = await _controller.canGoForward();
          setState(() {
            _canGoBack = back;
            _canGoForward = forward;
          });
        },
      ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('WebView with Controls')),
      body: Column(
        children: [
          Expanded(child: WebViewWidget(controller: _controller)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: _canGoBack ? () => _controller.goBack() : null,
              ),
              IconButton(
                icon: Icon(Icons.arrow_forward),
                onPressed: _canGoForward ? () => _controller.goForward() : null,
              ),
            ],
          ),
        ],
      ),
    );
  }
}

3. Refresh Navigation States

Each time a new page loads, we refresh _canGoBack and _canGoForward using onPageFinished. This ensures the buttons are enabled or disabled appropriately.

Conclusion

Adding back and forward buttons gives your WebView a familiar and user-friendly browsing experience. With a few simple lines of code, you can offer smooth navigation between pages within your Flutter app. In future tutorials, we’ll look at custom error pages, intercepting links, and loading progress indicators.

Comment

Copied title and URL