Home > Blockchain >  How to dismiss flutter dialog IF parent context is no more available?
How to dismiss flutter dialog IF parent context is no more available?

Time:09-25

The scenario is that I need to dismiss the dialog of the sign-in page after user is signed in. But after the user is signed in, the authentication branch is no longer available - meaning dialog's parent is nuked (the page that contains several auth options, it is replaced with home page due to user status listeners higher up the widget tree), so attempt to close the dialog programmatically like this fails

      Navigator.of(context, rootNavigator: true).pop();
//or  Navigator.of(context).pop();

The error that I receive reads

Looking up a deactivated widget's ancestor is unsafe [...]

How do I close that kind of floating dialog?

CodePudding user response:

Perhaps you should use the same context to build the sign-in widget (I mean the parent widget context), if you do so, your sign-in widget will be in the same navigation stack as the rest of the screens, therefore popping it should be safe...

You could take a look at my github repo...

https://github.com/casareafer2908/basic_routes_navigation

CodePudding user response:

Demo Widget


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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        ElevatedButton(
          onPressed: () {
            showDialog(
              context: context,
              builder: (dialogCTX) => AlertDialog(
                actions: [
                  ElevatedButton(
                    onPressed: () {
                      Navigator.of(dialogCTX).pop();

                      Navigator.of(dialogCTX).push(MaterialPageRoute(
                        builder: (context) => ChildW(),
                      ));
                    },
                    child: Text("Nav"),
                  ),
                ],
              ),
            );
          },
          child: const Text("opne dialog"),
        )
      ],
    ));
  }
}

class ChildW extends StatelessWidget {
  const ChildW({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Child"),
      ),
      body: ElevatedButton(
        onPressed: () {
          Navigator.of(context, rootNavigator: true).pop();
        },
        child: Text("POP"),
      ),
    );
  }
}


  • Related