Home > Blockchain >  how to close a specific dialog in flutter?
how to close a specific dialog in flutter?

Time:11-24

I want to close a specified dialog.

My case:

  • Open 2 dialogs (1) and (2), and 2 dialogs are showing at the same time. (2) is overriding (1) and I want to close (1) first.

With Android: I can assign each dialog to a variable and use dialog.dismiss().

I came across this example, it works but it doesn't seem to be the best way. How to close a specific Flutter AlertDialog?

Thanks for all the answers!

CodePudding user response:

As far as I know, you can't do that with Dialog because Dialog use Navigator, which use Stack only allow you to push and pop the top Route

Another option you can use to implement this is OverLayEntry, like this:

class _MyHomePageState extends State<MyHomePage> {
  OverlayEntry? _overlayEntry1;
  OverlayEntry? _overlayEntry2;

  @override
  void initState() {
    super.initState();

    _overlayEntry1 = OverlayEntry(
      builder: (context) {
        return Material(
          color: Colors.transparent,
          child: Center(
            child: Container(
              height: 300,
              width: 300,
              color: Colors.green,
            ),
          ),
        );
      },
    );

    _overlayEntry2 = OverlayEntry(
      builder: (context) {
        return Material(
          color: Colors.transparent,
          child: Center(
            child: InkWell(
              onTap: () {
                _overlayEntry1?.remove();
              },
              child: Container(
                height: 150,
                width: 150,
                color: Colors.red,
              ),
            ),
          ),
        );
      },
    );

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InkWell(
          onTap: () {
            Overlay.of(context)!.insert(_overlayEntry1!);
            Overlay.of(context)!.insert(_overlayEntry2!);
          },
          child: Text('Show overlay'),
        ),
      ),
    );
  }
}

CodePudding user response:

You can close the first dialogue before the second dialogue pops up by using Navigator.pop(context) or if you use GetX then you can use Get.back() before calling the second dialogue opening function.

If you want the first dialogue opens up after the second dialogue pops then you can try this:

When you close the second dialogue you will call the first dialogue up by using .then((e)=> 'previous dialogue open function goes here').

So at the same time, no two dialogues are opened. Just use them one by one.

  • Related