build method

  1. @override
Widget build()
override

Subclasses should override this function to actually call the appropriate build function (e.g., StatelessWidget.build or State.build) for their widget.

Implementation

@override
Widget build() {
  // Inherited を取得(依存関係を張るため build 内で取得)
  final next = ProviderScope.of(this);
  if (!identical(_container, next)) {
    for (final c in _cancels.values) {
      c.close();
    }
    _cancels.clear();
    _container = next;
  }

  _watchedThisBuild.clear();

  final ref = _WidgetRefImpl(
    container: _container!,
    onWatch: <S>(ProviderBase<S> provider) {
      final k = provider.key.toString();
      _watchedThisBuild.add(k);
      if (!_cancels.containsKey(k)) {
        final cancel = _container!.listen<S>(provider, (_, _) {
          _markNeedsBuildSafely();
        });
        _cancels[k] = cancel;
      }
    },
  );

  final w = widget as ConsumerWidget;
  final child = w.build(this, ref);

  // 今回の build で参照しなかった購読を解除
  final toRemove = _cancels.keys
      .where((k) => !_watchedThisBuild.contains(k))
      .toList();
  for (final k in toRemove) {
    _cancels.remove(k)?.close();
  }

  return child;
}