Flutter WebView with WillPopScope not working as expected

Viewed 272

I have implemented Flutter Webview using webview_flutter: ^0.3.3 dependency.

My flow is:

Splash Screen -> Home Page (2 buttons, Login and Explore) -> Login Page

if already pressed Login once then it will open LoginPage directly.

Let me share code:

splash_screen.dart

  Future<void> doSomeAsyncStuff() async {
    final prefs = await SharedPreferences.getInstance();
    isLogin = prefs.getBool('isLogin') ?? false;

    new Future.delayed(const Duration(seconds: 3), () {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => isLogin ? LoginPage() : HomePage()));
    });
  }

home_page.dart

  // Login Button Click, Here I am saving preference for login.
  // So I can come to login directly when I open the app.
  Future<void> openLoginPage() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setBool('isLogin', true);
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => LoginPage()));
  }

  // Explore Button Click
  void openExplorePage() {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => ExplorePage()));
  }

login_page.dart

// I AM GETTING PROBLEM HERE...
// WHEN I AM PRESSING BACK BUTTON.. I WANT TO EXIT FROM APP BUT BECAUSE OF THERE IS NOTHING IN BACK STACK, IT IS NOT DOING ANYTHING.
// IF I HAVE SOMETHING IN BACK STACK OF WEBVIEW, IT WILL GO TO BACK PAGE but PROBLEM IS ONLY WHEN I WANT TO EXIT FROM APP.
Future<bool> _exitApp(BuildContext context) async {
  if (await controllerGlobal.canGoBack()) {
    controllerGlobal.goBack();
  } else {
    Navigator.of(context).pop();
    return Future.value(true);
  }
}

Can anyone help me?

1 Answers

In SplashScreen you have used Navigator.push() to move to the login screen so it have SplashScreen on the back stack. Use Navigator.pushReplacement instead of Navigator.push() it will replace the previous screen.

new Future.delayed(const Duration(seconds: 3), () {
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) => isLogin ? LoginPage() : HomePage()));
    });
Related