Any one can config to me the backbutton on flutter for this code?

162 views Asked by At

When i press the back-button of the device the app close, so I want to config the back-button of the device to go back in sequences pages not to exit .Thank you

import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Welcome to Flutter',
          home: Scaffold(
            body: WebView(
              initialUrl: "https://www.carrefourjordan.com",
              javascriptMode: JavascriptMode.unrestricted,
            ),
          ),
        );
      }
    }
2

There are 2 answers

2
Azad Prajapat On

hi there to manage back button press use Willpopscope by wraping scaffold inside willpopscope and use onwillpop property

WillPopScope(
  onWillPop: (){
   // Navigator.push(context, MaterialPageRoute(builder: (context)=>Page()));
       return Future.value(false);
  },
  child: Scaffold(
    body: WebView(
      initialUrl: "https://www.carrefourjordan.com",
      javascriptMode: JavascriptMode.unrestricted,
    ),
  ),
);
0
Sisir On

You can do achieve this in 2 steps:

  1. Wrap your Scaffold within a WillPopScope to capture the back button press event
  2. Use the webview package InAppWebView controller's canGoback() and goBack() to move in the WeView

Try this:

  class MyApp extends StatelessWidget {
  InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Welcome to Flutter',
      home: WillPopScope(
        onWillPop: _onBack,
        child: Scaffold(
          body: InAppWebView(
            initialUrl: "https://www.carrefourjordan.com",
            onWebViewCreated: (InAppWebViewController controller) {
              _webViewController = controller;
            },
          ),
        ),
      ),
    );
  }

  Future<bool> _onBack() async {
    if (await _webViewController.canGoBack()) {
      _webViewController.goBack(); // perform webview back operation
      return false;
    } else {
      // Webpage in home page
      return true; // Close App
    }
  }
}