跳到正文
教程首页
FlutterCH 11ch11_state_management

ch11-state-management

状态管理:从 setState 到 InheritedWidget 再到 Riverpod。完整工程共 105 个文件,其中 65 个文本源文件可在下面在线阅读。

65

在线文本文件

4,024

源码行数

dart / c / yaml

语言

284 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

textxmldartjsonkotlin

65 text files · 4,024 lines

dartlib/src/inherited_counter.dart
// 层次 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<ValueNotifier<int>> {
  const CounterScope({
    super.key,
    required ValueNotifier<int> counter,
    required super.child,
  }) : super(notifier: counter);

  static ValueNotifier<int> of(BuildContext context) {
    final CounterScope? scope = context.dependOnInheritedWidgetOfExactType<CounterScope>();
    assert(scope != null, 'CounterScope 不在祖先链上');
    return scope!.notifier!;
  }
}

/// 作用域宿主:负责创建/销毁 notifier。
class InheritedCounterDemo extends StatefulWidget {
  const InheritedCounterDemo({super.key});

  @override
  State<InheritedCounterDemo> createState() => _InheritedCounterDemoState();
}

class _InheritedCounterDemoState extends State<InheritedCounterDemo> {
  final ValueNotifier<int> _counter = ValueNotifier<int>(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<int> 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<int> counter = CounterScope.of(context);
    return Chip(
      key: const Key('inh-parity'),
      label: Text(counter.value.isEven ? '偶数' : '奇数'),
    );
  }
}

代码构成:text 62 KB · xml 41 KB · dart 29 KB · json 4 KB

本地运行

zip → 解压 → 执行
$cd examples/ch11-state-management && flutter run -d macos

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • flutter analyze 0 告警、flutter test 11 个用例全绿、flutter build macos --debug 真实构建并启动成功
查看全部示例