Home > Back-end >  How do I push to a screen and hide the backstack until something happens in that screen?
How do I push to a screen and hide the backstack until something happens in that screen?

Time:06-07

Here's the thing: I have Screen 1 and I want to navigate to Screen 2, but I don't want the user to be able to go back until they press a button on that screen. Once the button has been pressed, I want it to return the user to Screen 1, popping Screen 2. Any ideas on how I can achieve this?

Also, I want the state of Screen 1 to be maintained, so the pushReplacementNamed method doesn't work for this situation.

CodePudding user response:

You can use the WillPopScope widget for this like so:

class SecondScreen extends StatefulWidget {
  const SecondScreen({Key? key}) : super(key: key);

  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  bool canPop = false;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: canPop ? null : () async => false,
      child: Scaffold(
        body: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                setState(() {
                  canPop = true;
                });
              },
              child: const Text('Target Button'),
            ),
          ],
        ),
      ),
    );
  }
}
  • Related