Home > OS >  Showing warning: Do not use BuildContexts across async gaps
Showing warning: Do not use BuildContexts across async gaps

Time:01-09

if (_formKey.currentState!.validate()) {
                      try {
                        final newUser =
                            await _auth.createUserWithEmailAndPassword(
                                email: email.text, password: password.text);
                        if (newUser != null) {
                          // Navigator.push(
                          //     context,
                          //     MaterialPageRoute(
                          //       builder: (context) => DashboardScreen(),
                          //     ));
                          Navigator.pushNamed(context, 'dashboard');
                        }

                        setState(() {});
                      } catch (e) {
                        print(e);
                      }
                    }
                  },

this warning shown on Navigator.pushNamed(context,'dashboard'); trying to navigate to the dashboar screen.

enter image description here

CodePudding user response:

1. You have to put delay for other process can finish till then

 Future.delayed(Duration(milliseconds: 200)).then((value) {
      Navigator.pushNamed(context, 'dashboard')
});

2. add if (!mounted) return; before Navigator.pushNamed(context, 'dashboard')

3. Please put await before the navigator flutter because you used an asynchronously method call so you have to wait until the process is finished then you can navigate to your pages

 await Navigator.pushNamed(context, 'dashboard');

4. Also, you can store your navigator into a var and then use it.

 final nav = Navigator.of(context);
 nav.pushNamed('dashboard');
  • Related