Search code examples
flutterwebviewandroid-webviewback-button

How to make device back button to go to the previous page in flutter webview


I have some simple code here that just displays a webpage. I want to make it so that, pressing the device back button takes you to the previous page on the webview. I tried looking for solutions online but was unable to integrate any of them into my code. Kindly help me out.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Mobile App",
      home: Scaffold(
          body: SafeArea(
              child: WebView(
        initialUrl: 'https://flutter.dev',
        javascriptMode: JavascriptMode.unrestricted,
      ))),
      debugShowCheckedModeBanner: false,
    );
  }

}

Solution

  • Wrap Scaffold with this widget

    WillPopScope(
      onWillPop: controller.onBackPressedHandler,
      child: Scaffold( ... )
    
    Future<bool> onBackPressedHandler() {
    
    return Future.value(false);} //return false disables default functionality
    

    you can control back button functionality in onBackPressedHandler function. For your case you should put this line of code inside it

    webviewController.goBack();