change_notifier_manage.dart
2.09 KB
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
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// @weilu https://github.com/simplezhli/flutter_deer
///
/// 便于管理ChangeNotifier,不用重复写模板代码。
/// 之前:
/// ```dart
/// class TestPageState extends State<TestPage> {
/// final TextEditingController _controller = TextEditingController();
/// final FocusNode _nodeText = FocusNode();
///
/// @override
/// void initState() {
/// _controller.addListener(callback);
/// super.initState();
/// }
///
/// @override
/// void dispose() {
/// _controller.removeListener(callback);
/// _controller.dispose();
/// _nodeText.dispose();
/// super.dispose();
/// }
/// }
/// ```
/// 使用示例:
/// ```dart
/// class TestPageState extends State<TestPage> with ChangeNotifierMixin<TestPage> {
/// final TextEditingController _controller = TextEditingController();
/// final FocusNode _nodeText = FocusNode();
///
/// @override
/// Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
/// return {
/// _controller: [callback],
/// _nodeText: null,
/// };
/// }
/// }
/// ```
mixin ChangeNotifierMixin<T extends StatefulWidget> on State<T> {
Map<ChangeNotifier?, List<VoidCallback>?>? _map;
Map<ChangeNotifier?, List<VoidCallback>?>? changeNotifier();
@override
void initState() {
_map = changeNotifier();
/// 遍历数据,如果callbacks不为空则添加监听
_map?.forEach((changeNotifier, callbacks) {
if (callbacks != null && callbacks.isNotEmpty) {
void _addListener(VoidCallback callback) {
changeNotifier?.addListener(callback);
}
callbacks.forEach(_addListener);
}
});
super.initState();
}
@override
void dispose() {
_map?.forEach((changeNotifier, callbacks) {
if (callbacks != null && callbacks.isNotEmpty) {
void _removeListener(VoidCallback callback) {
changeNotifier?.removeListener(callback);
}
callbacks.forEach(_removeListener);
}
changeNotifier?.dispose();
});
super.dispose();
}
}