getx icon indicating copy to clipboard operation
getx copied to clipboard

BUG: Getx 5.x WillPopScope press the back button cannot be intercepted

Open lijinshanmx opened this issue 2 years ago • 2 comments

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

import 'index.dart';

class TestPage extends GetView<TestController> {
  const TestPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: Scaffold(
          appBar: AppBar(
            title: const Text('TestPage'),
          ),
          body: Container()),
    );
  }
}


When the phone back button is pressed, although onWillPop returns false, the current page will still be closed. Version 4.6.5 does not have this problem.

lijinshanmx avatar Feb 23 '23 11:02 lijinshanmx

Maybe use BackButtonListener

N0Noorz avatar Feb 25 '23 04:02 N0Noorz

The Solution =

  • Show AlertDialog when user Press back Button and GoBack or Stay on the same Page According to User Action ( Yes or No ) [ Logic ] ⇒
@override
  Widget build(BuildContext context) {
    // Back Navigation Logic while using AlertDialog
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) async {
        // if true then return nothing
        if (didPop) {
          return;
        }
        // if false then return AlertDialog Widget
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            title: const Text('Do you want to Edit this ?'),
            actions: [
              OutlinedButton(
                onPressed: () {
                  // if user click on Yes then,

                  // First close the Dialog
                  Get.back();
                  // Then close the current page and go back
                  Get.back();
                },
                child: const Text('Yes'),
              ),
              OutlinedButton(
                onPressed: () {
                  // if user click on No then,

                  // Just close the dialog
                  Get.back();
                },
                child: const Text('No'),
              ),
            ],
          ),
        );
      },
      child: Scaffold();

======================================================================

Completely Tested on Production App.

It is Working Fine ! 👍

Rahul-Sharma-Github avatar Feb 05 '24 13:02 Rahul-Sharma-Github