👨‍👧‍👦

【Flutter】InheritedWidgetの使い方を理解する

2022/03/27に公開

InheritedWidgetは下位ツリーのWidgetから上位ツリーのWidgetで管理している状態にアクセスする手段を提供したり、上位ツリーのWidgetで管理している状態が更新された時に、変更を下位ツリーのウィジェットに通知する機能を持ったWidgetです。同様の手段を提供しているProviderパッケージはInheritedWidgetをラップしたパッケージになります。Providerパッケージの普及によりInheritedWidgetを使用する機会はほとんど無くなってきていますが、InheritedWidgetの仕組みを理解することでProviderパッケージへの理解を深めることができます。
https://youtu.be/1t-8rBCGBYw

InheritedWidgetの特徴

  • 下位ツリーのウィジェットからO(1)[1]でアクセスすることができる。
  • InheritedWidgetが持つ状態が変更された時、その状態にアクセスしたWidgetに対して必要に応じて変更を通知することができる(リビルドさせることができる)。

InheritedWidgetへのアクセスと変更通知

InheritedWidgetへアクセスする方法は2つあり、それぞれ特徴に若干の違いがあります。

  • dependOnInheritedWidgetOfExactType
  • getElementForInheritedWidgetOfExactType

dependOnInheritedWidgetOfExactType

context.dependOnInheritedWidgetOfExactType<HogeWidget>()
  • dependOnInheritedWidgetOfExactType<HogeWidget>を呼び出したcontextから、最も近いHogeWidget(InheritedWidgetを継承したWidget)を返す。
  • dependOnInheritedWidgetOfExactType<HogeWidget>を使用してHogeWidgetが持つ状態にアクセスしたWidgetに対して、その状態が変更される度に変更を通知することができる(リビルドさせることができる)。
  • didChangeDependencies以降のタイミングでしか呼べない。

getElementForInheritedWidgetOfExactType

context.getElementForInheritedWidgetOfExactType<HogeWidget>()
  • getElementForInheritedWidgetOfExactType<HogeWidget>を呼び出したcontextから、最も近いHogeWidget(InheritedWidgetを継承したWidget)を返す。
  • getElementForInheritedWidgetOfExactType<HogeWidget>を使用してHogeWidgetが持つ状態にアクセスしたWidgetに対して、その状態が変更されても変更が通知されない(リビルドされない)。
  • initStateタイミングでも呼べる。

実装

サンプルソースは以下に置いています。
https://github.com/NAOYA-MAEDA-DEV/flutter_inherited_sample
フローティングボタンをタップした回数を表示するシンプルなアプリです。動作検証の為、上側のTextウィジェットはタップした回数の表示を更新しますが、下側のTextウィジェットはタップした回数の表示を更新しないようにしています。

main.dart
class _InheritedCounter extends InheritedWidget {
  const _InheritedCounter(
      {Key? key,
        required Widget child,
        required this.count
      }): super(key: key, child: child);

  final int count;

  
  bool updateShouldNotify(_InheritedCounter old) => true;

  static _InheritedCounter? of(BuildContext context, {required bool listen}) {
    return listen
        ? context.dependOnInheritedWidgetOfExactType<_InheritedCounter>()
        : context.getElementForInheritedWidgetOfExactType<_InheritedCounter>()?.widget as _InheritedCounter;
  }
}

class _CounterPage extends StatefulWidget {
  const _CounterPage({Key? key}): super(key: key);

  
  _CounterPageState createState() => _CounterPageState();
}


class _CounterPageState extends State<_CounterPage> {
  var _count = 0;

  
  Widget build(BuildContext context) {
    print('Built CounterPageState');

    return
      _InheritedCounter(
        count: _count,
        child: Scaffold(
          appBar: AppBar(title: const Text('Inherited Widget Sample')),
          floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: _increment,
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              WidgetA(),
              WidgetB()
            ],
          )),
        );
  }

  void _increment() {
    setState(() {
      _count++;
    });
  }
}

class WidgetA extends StatelessWidget {
  const WidgetA({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    print('Built WidgetA');

    return Center(
        child: Text(
            'CounterA: ${_InheritedCounter.of(context, listen: true)?.count}',
            style: const TextStyle(
                fontSize: 20
            )
        )
    );
  }
}

class WidgetB extends StatelessWidget {
  const WidgetB({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    print('Built WidgetB');

    return Center(
        child: Text(
            'CounterA: ${_InheritedCounter.of(context, listen: false)?.count}',
            style: const TextStyle(
                fontSize: 20
            )
        )
    );
  }
}

サンプルソースの解説

InheritedWidgetを継承した状態クラスを作る

  • 下位ツリーのWidgetがアクセスするフィールド(状態)を用意する
final int count;

実装例ではcountが下位ツリーのWidgetからアクセスするフィールドとなっています。

  • ofメソッドで自身にアクセスする手段を提供する
static _InheritedCounter? of(BuildContext context, {required bool listen}) {
  return listen
      ? context.dependOnInheritedWidgetOfExactType<_InheritedCounter>()
      : context.getElementForInheritedWidgetOfExactType<_InheritedCounter>()?.widget as _InheritedCounter;
}

Flutterでの慣例として自身にアクセスするためのメソッドであるofメソッドを定義します。前項のdependOnInheritedWidgetOfExactTypegetElementForInheritedWidgetOfExactTypeを使用して自身にアクセスする手段を提供します。listenがtrueの時は変更の通知が行われるdependOnInheritedWidgetOfExactTypeを実行、listenがfalseの時は変更の通知が行われないgetElementForInheritedWidgetOfExactTypeを実行しています。

  • updateShouldNotifyで変更の通知条件を設定する

bool updateShouldNotify(_InheritedCounter old) => true;

trueを返した時はフィールドの変更が下位ツリーのWidgetに通知され、falseを返した時はフィールドの変更が下位ツリーのWidgetに通知されなくなります。これによりフィールドの変更内容によって通知を制限することができます。

上位ツリーにInheritedWidget配置する

上位ツリーに前項で作成した_InheritedCounterを配置します。_InheritedCounterのcountプロパティに下位ツリーのWidgetからアクセスするプロパティをセットし、childに下位ツリーとなるWidgetを配置していきます。

_InheritedCounter(
  count: _count,
  child: ...
)

下位ツリーのWidgetから直近のInheritedWidgetにアクセスする

_InheritedCounterで定義したofメソッドを使用して、直近のInheritedWidgetのフィールドにアクセスすることができます。

_InheritedCounter.of(context, listen: true)?.count

WidgetA内ではofメソッドの引数listenをtrue、WidgetB内ではofメソッドの引数listenをfalseとしています。フローティングボタンをタップしてcountをインクリメントした時、countの変更通知を受け取るWidgetAはリビルドされ、カウントの更新がTextウィジェットに反映されます。しかしcountの変更通知を受け取らないWidgetBはリビルドされず、カウントの更新がTextウィジェットに反映されないようになっています。

実行結果

フローティングボタンをタップするとsetStateが実行され、_CounterPageStateがリビルドされます。WidgetA、WidgetBはconst指定されており、リビルドされないようになっています。しかし、WidgetA内では

_InheritedCounter.of(context, listen: true)?.count

とlistenをtrueにして、_InheritedCounterの状態を監視しています。その結果、フローティングボタンをタップして_InheritedCounterのcountがインクリメントされたことを検知し、const指定をしているWidgetAはリビルドされるようになっています。

脚注
  1. ランダウ記号と呼ばれる処理にかかる計算量表を表す時に使用される。下位ツリーウィジェットからアクセス先のInheritedWidgetの距離が大きくなってもアクセス時間は一定となる。 ↩︎

Discussion