17
10

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 5 years have passed since last update.

StatefulWidgetのinitStateでcontextにアクセスできるか

Last updated at Posted at 2019-05-20

やりたいこと。

StatefulWidgetの初期化時にcontextにアクセスしたい

結論

できません。

代替案

didChangeDependenciesを使用します。

Stateのライフサイクルは

  1. createState
  2. initState
  3. didChangeDependencies

のように進みます。

3のdidChangeDependenciesはinitStateの直後に呼ばれます。

ここでは、contextにアクセスが必要なInheritedWidget由来のinheritFromWidgetOfExactTypeにアクセスすることができます。

didChangeDependenciesの公式ドキュメントより、

This method is also called immediately after initState. It is safe to call BuildContext.inheritFromWidgetOfExactType from this method.

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  final String hoge = fuge.of(context).piyo;
}

参考

Flutter公式ドキュメント -didChangeDependenciesについて-
Stack Overflow

17
10
2

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
17
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?