🙆

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

に公開

はじめに

端末の画像を読み込んで表示するソースコードを書いていた際に下記のメッセージが発生

Don't use 'BuildContext's across async gaps.
Try rewriting the code to not use the 'BuildContext', or guard the use with a 'mounted' check.

解決策

メッセージの通り、BuildContextが非同期処理で使用されていることが原因。非同期処理中にWidgetがunmountされる可能性も考えられるので、無効なcontextが使用されることを防ぐ必要がある。

BuildContextを非同期処理で使用する場合は、Widgetがmountされているかどうか(アクティブかどうか)をmountedプロパティを使ってチェックする。

//修正前
onTap: () async {
  XFile? xfile = await imagePicker.pickImage(
      source: ImageSource.gallery);
  if (xfile != null) {
    File image = File(xfile.path);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          return RecognizerScreen(image);
        },
      ),
    );
  }
},
//修正後
onTap: () async {
  XFile? xfile = await imagePicker.pickImage(
      source: ImageSource.gallery);
  if (xfile != null) {
    File image = File(xfile.path);
    if (context.mounted) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) {
            return RecognizerScreen(image);
          },
        ),
      );
    }
  }
},

参考

https://api.flutter.dev/flutter/widgets/BuildContext/mounted.html

Discussion