Hung Nguyen
Hung Nguyen

Reputation: 11

How to ensure that a dialog only appears on the screen where the 'showDialog' function is called in Flutter

I have two screens A and B. I am currently on screen A and I call a function that displays a dialog after 10 seconds. The problem is that when I navigate to screen B before the dialog appears, the dialog appears on screen B instead of A, even though I have used _scaffoldKey.currentContext.

showDialog(
      context: _scaffoldKey.currentContext!,
      builder: (ctx) {
        return Widget();
      },
    )

i use Navigator.of(context).pushNamed('/screenB) to navigate to screen B.

How can I ensure that the dialog only appears on screen A?

Upvotes: 0

Views: 565

Answers (1)

Ali Jawad
Ali Jawad

Reputation: 376

Hung.

The issue may be due to the fact that you are passing in the current context of _scaffoldKey at the time the showDialog method is called. However, if you navigate to screen B before the dialog appears, then the current context may no longer refer to screen A.

Instead of explicitly relying on _scaffoldKey.currentContext, One way to do is by wrapping the widget with Builder

class ScreenA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context) {
          return Center(
            child: ElevatedButton(
              child: Text('Show Dialog'),
              onPressed: () {
                Future.delayed(Duration(seconds: 10), () {
                  showDialog(
                    context: context, // Pass in the context of the Builder widget
                    builder: (ctx) {
                      return AlertDialog(
                        title: Text('Dialog'),
                        content: Text('This dialog will always appear on Screen A'),
                        actions: [
                          TextButton(
                            child: Text('OK'),
                            onPressed: () {
                              Navigator.of(ctx).pop();
                            },
                          ),
                        ],
                      );
                    },
                  );
                });
              },
            ),
          );
        },
      ),
    );
  }
}

Hope it help, Also the basic definition of context to clear your mind further,

– Context is a link to the location of a widget in the tree structure of widgets. – Context can belong to only one widget. – If a widget has child widgets, then the context of the parent widget becomes the parent context for the contexts of direct child elements.

Upvotes: 0

Related Questions