0
0

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

InheritedWidgetをざっくり理解する

Last updated at Posted at 2020-05-08

Flutter学習中に、InheritedWidgetがとっつきにくかったので、
その特徴等、超ざっくり書き留めておこうと思います。
PJ内初心者メンバーに手短に説明する際に役立てば良いなと。

※以下の記事を自分なりに噛み砕いた内容になっています。
InheritedWidget を完全に理解する
分かりやすく具体的に書かれており大変参考になりました。

InheritedWidgetの特徴

  • child Widgetから、上位のWidgetに高速にアクセスできる。

  • 変更を特定のchild Widgetのみに伝番させる(リビルドさせる)ことが出来る。

前者については、InheritedWidgetでなくても、
BuildContext.findAncestorWidgetOfExaxtTypeを使ってアクセスは可能だが、
これはツリーを順に走査するため、計算量がO(N)となり高速とはいかない。
InheritedWidgetではO(1)でアクセスできる。

後者については、InheritedWidgetには、自身を返す機能が大きく以下の2つあるので、
child widgetから、そのどちらを呼ぶかを使い分けて実現できる。

  • dependOnInheritedWidgetOfExactType
    Widgetの変更を監視して、変更があったときに最新の状態を伝番することが出来る。
    なお、変更の監視を行うため、didChangeDependencies以降のタイミングでしか呼べない。

  • getElementForInheritedWidgetOfExactType
    単にInheritedWidgetビルド時点のElementを取得する。
    なお、監視しないので、initSateでも呼べる。

使い方

上位WidgetをInheritedWidgetを継承して作り、
それに、自身を返す(引数にBuildContextを持つ)のようなFunctionを用意する。
自身を返す際には、
context.dependOnInheritedWidgetOfExactType() もしくは、
context.getElementForInheritedWidgetOfExactType() で返すようにする。
変更がある度に最新ものを伝番したい場合は、前者で返すようにする。
変更があっても伝番したくない場合は、後者で返すようにする。

そして、その上位Widgetのchildに設置したWidgetから、
上位widgetで実装した自身を返すFunction を呼ぶ事で、
上位Widgetが取得でき、そのプロパティを取得できる。

そんな感じ。
次はProviderのお勉強かな。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?