示例工程 ch11-state-management
ch11-state-management/lib/src/home_page.dart
// 首页:把四种状态管理手段放在一起对照。
import 'package:flutter/material.dart';
import 'change_notifier_cart.dart';
import 'inherited_counter.dart';
import 'riverpod_cart_page.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('状态管理:四种层次')),
body: ListView(
padding: const EdgeInsets.all(16),
children: const [
_Section(
index: '1',
title: 'InheritedWidget + ValueNotifier',
subtitle: '框架原生:沿树传递 + 依赖订阅(Theme.of 就是这个机制)',
child: InheritedCounterDemo(),
),
_Section(
index: '2',
title: 'ChangeNotifier + ListenableBuilder',
subtitle: '模型自己通知;跨页共享还得靠传参或 InheritedWidget',
child: ChangeNotifierCartDemo(),
),
_Section(
index: '3',
title: 'Riverpod:Notifier + Provider',
subtitle: '状态在 Widget 树之外,任何页面 ref.watch 都能拿到',
child: RiverpodCartSection(),
),
],
),
);
}
}
class _Section extends StatelessWidget {
const _Section({
required this.index,
required this.title,
required this.subtitle,
required this.child,
});
final String index;
final String title;
final String subtitle;
final Widget child;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Card(
margin: const EdgeInsets.only(bottom: 12),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 12,
backgroundColor: theme.colorScheme.primary,
child: Text(index, style: const TextStyle(fontSize: 12, color: Colors.white)),
),
const SizedBox(width: 8),
Expanded(child: Text(title, style: theme.textTheme.titleMedium)),
],
),
Text(
subtitle,
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
const Divider(height: 16),
child,
],
),
),
);
}
}