LoginSignup
1
1

【Flutter】Do not use BuildContexts across async gaps の対処法

Posted at

背景

非同期処理を含むメソッドonTap()の中で画面のpush遷移を行おうとしたところコンパイラから忠告を受けた

onTap: () async {
  final user = await firebaseAuth.signInWithGoogle();
  if (user != null) {
      context.Navigator.of(this).push(somePage());// Do not use BuildContexts across async gaps
  } else {
    debugPrint('login failed');
  }
},

原因

非同期処理が走るasync内でBuild Contextを使用すると、contextに差分が生じて、元のcontextとは異なるcontextを参照する恐れがあるから。

今回の場合は、contextWidget Treeから削除されている可能性があるため警告が出た。

対処法

contextWidget Treeから削除されていないかmouted propertyで確認する
HookWidgetを使用している場合は useIsMouted()からmountされているか否か確認する。

onTap: () async {
  final user = await firebaseAuth.signInWithGoogle();
  if (user != null) {
    if (context.mounted) {
      context.Navigator.of(this).push(somePage());// Do not use BuildContexts
    }
 across async gaps
  } else {
    debugPrint('login failed');
  }
},
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1