Don't use 'BuildContext's across async gaps.

This issue has been tracked since 2023-03-18.

Steps to Reproduce

I want to route to PageNavigation after login, and I need to sure login() returns true before the navigate action , but there's a warning after I update flutter to 3.7.3, thank u so much to help me out though it doesn't affect my app now.

                          onPressed: () async {
                            if (_formKey.currentState!.validate()) {
                              if (await login()) {
                                Navigator.push(context, MaterialPageRoute(builder: (context) {
                                  return const PageNavigation();
                                }));
                              }
                            }
                          },

Expected results:
no warnings
Actual results:
Don't use 'BuildContext's across async gaps.

iapicca wrote this answer on 2023-03-18

@gkdgo
not a bug, you need to check if context is mounted

import 'package:flutter/material.dart';

Future<bool> login() => Future.delayed(const Duration(seconds: 1), () => true);

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(context) => Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            if (await login()) {
              if (context.mounted) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const PageNavigation(),
                  ),
                );
              }
            }
          },
        ),
      );
}

class PageNavigation extends StatelessWidget {
  const PageNavigation({super.key});

  @override
  Widget build(context) => const Material(
        child: Center(
          child: Text('you are logged in'),
        ),
      );
}
gkdgo wrote this answer on 2023-03-18

@iapicca
Thanks for ur quick response , it really helps , I am gone to close the issue

iapicca wrote this answer on 2023-03-19

@gkdgo
happy to help!
If I can give a recommendation, the packages

  • go_router for navigation
  • riverpod for state management (like the state of the login)

could simplify your life as your app grows more comples

gkdgo wrote this answer on 2023-03-19

@gkdgo happy to help! If I can give a recommendation, the packages

  • go_router for navigation
  • riverpod for state management (like the state of the login)

could simplify your life as your app grows more comples

of course , I will take them into account in my future coding

More Details About Repo
Owner Name flutter
Repo Name flutter
Full Name flutter/flutter
Language Dart
Created Date 2015-03-06
Updated Date 2023-03-30
Star Count 151602
Watcher Count 3555
Fork Count 25000
Issue Count 11498

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date