3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flutterのcontext.mountedについて

Posted at

はじめに

備忘録的に残します。
ミスや補足があればご指摘お願いします。

context.mountedとは

context.mountedは現在のWidgetがツリーに取り付けられているかをチェックするための手法。
Widgetが取り付けられていればtrueとなり、そうでなければfalseとなります。

使用例

非同期処理のが終了した時にその結果を反映させたい場面があるかと思います。例えば、処理が終わったタイミングでダイアログをpopしたい場合などです(今回はその用途で使いました。ignoreを使わずに、if(context.mounted)を用いることで、エラーを回避できたりします。

サンプルコード
Future<void> nyan() async {
  var pyoe = await feadCat(); // 何らかの非同期処理
  if (context.mounted) {
    setState(() {
      // 状態の更新
    });
  }
}

正し、これを多用するよりも根本的な問題を解決する方法を探した方がよさそうに感じましたっ!

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?