Elias
Elias

Reputation: 453

Flutter "Do not use BuildContexts across async gaps"

Basically I want to return to my LoginView when the user presses Logout in the dialog.

onSelected: (value) async {
              switch (value) {
                case MenuAction.logout:
                  final shouldLogout = await showLogOutDialog(context);
                  final navigator = Navigator.of(context);
                  if (shouldLogout) {
                    await FirebaseAuth.instance.signOut();
                    navigator.pushNamedAndRemoveUntil(
                      '/login',
                      (route) => false,
                    );
                  }
              }
            },

showLogoutDialog function:

Future<bool> showLogOutDialog(BuildContext context) {
  return showDialog<bool>(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: const Text('Sign out'),
        content: const Text('Are you sure you want to sign out?'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(false);
            },
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(true);
            },
            child: const Text('Logout'),
          ),
        ],
      );
    },
  ).then((value) => value ?? false);

I get this error: "Do not use BuildContexts across async gaps.". Error at Navigator.of(contex

Anyone who can help me?

Thanks in advance!

Upvotes: 7

Views: 5821

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63559

It is unsafe, try checking if the widget is not mounted as shown on the Flutter YouTube Channel.

if (!mounted) return
Navigator.of(context);

Upvotes: 17

Related Questions