1

if i directly call the navigator.pushnamed method I receive a message that says, Don't use 'BuildContext's across async gaps. I don't know how to solve this problem and move to next screen. this is the code

                color: Colors.blueAccent,
                title: 'Register',
                onPressed: () async {
                  try {
                    final newUser = await _auth.createUserWithEmailAndPassword(
                        email: email, password: password);
                    if (newUser.user != null) {
                      await Future.delayed(Duration.zero);
                      Navigator.of(context).pushNamed(ChatScreen.id);
                    }
                  } catch (e) {
                    print(e);
                  }
                },
              ),
    ```
Fred_Wolfe
  • 658
  • 1
  • 7
  • 18
  • Does this answer your question? [Do not use BuildContexts across async gaps](https://stackoverflow.com/questions/68871880/do-not-use-buildcontexts-across-async-gaps) – MendelG Aug 06 '23 at 11:59

1 Answers1

1

When doing asynchronous tasks during widget's synchronous operations, you must check the widget is still available.

For your case, right before the Navigator line, add this line

if (!mounted) return;

By doing so you check the current Widget is mounted and usable. If the Widget is being rebuilt or destroyed, checking if it's mounted will return false.

If it returns true it means the Widget is ready and you can use async / sync tasks almost everywhere.

If this doesn't help or doesn't suit your case, please let me know and I'll provide more support, happy coding!

ItzDavi
  • 443
  • 4
  • 13