// 层次 2:InheritedWidget —— 框架原生的"沿树传递 + 依赖订阅"机制。 // // `Theme.of(context)`、`MediaQuery.of(context)` 都是这个模式: // 祖先放数据 → 后代 `dependOnInheritedWidgetOfExactType` 订阅 → 数据变就重建后代。 // // 手写一遍才明白 Riverpod 在替我们做什么: // 1. 找到最近的作用域; // 2. 注册依赖(谁依赖谁); // 3. 变化时精准通知(而不是重建整棵树)。 import 'package:flutter/material.dart'; /// `InheritedNotifier` 是 InheritedWidget 的"可监听"版本: /// 它内部监听 notifier,变化时自动通知所有依赖者,不用手写 `updateShouldNotify`。 class CounterScope extends InheritedNotifier> { const CounterScope({ super.key, required ValueNotifier counter, required super.child, }) : super(notifier: counter); static ValueNotifier of(BuildContext context) { final CounterScope? scope = context.dependOnInheritedWidgetOfExactType(); assert(scope != null, 'CounterScope 不在祖先链上'); return scope!.notifier!; } } /// 作用域宿主:负责创建/销毁 notifier。 class InheritedCounterDemo extends StatefulWidget { const InheritedCounterDemo({super.key}); @override State createState() => _InheritedCounterDemoState(); } class _InheritedCounterDemoState extends State { final ValueNotifier _counter = ValueNotifier(0); @override void dispose() { _counter.dispose(); super.dispose(); } void _bump(int delta) => _counter.value += delta; @override Widget build(BuildContext context) { return CounterScope( counter: _counter, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Row( children: [ _CounterLabel(), SizedBox(width: 16), _CounterParity(), // 两个互不相干的兄弟组件共享同一份状态 ], ), const SizedBox(height: 8), Wrap( spacing: 8, children: [ FilledButton(key: const Key('inh-inc'), onPressed: () => _bump(1), child: const Text('+1')), OutlinedButton( key: const Key('inh-dec'), onPressed: () => _bump(-1), child: const Text('-1'), ), TextButton( key: const Key('inh-reset'), onPressed: () => _counter.value = 0, child: const Text('归零'), ), ], ), ], ), ); } } class _CounterLabel extends StatelessWidget { const _CounterLabel(); @override Widget build(BuildContext context) { // 只有调用 of() 的 widget 才会在值变化时重建。 final ValueNotifier counter = CounterScope.of(context); return Text( 'count = ${counter.value}', key: const Key('inh-count'), style: Theme.of(context).textTheme.headlineSmall, ); } } class _CounterParity extends StatelessWidget { const _CounterParity(); @override Widget build(BuildContext context) { final ValueNotifier counter = CounterScope.of(context); return Chip( key: const Key('inh-parity'), label: Text(counter.value.isEven ? '偶数' : '奇数'), ); } }