1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import 'package:flutter/material.dart';
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!;
}
}
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) {
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 ? '偶数' : '奇数'),
);
}
}