-
Notifications
You must be signed in to change notification settings - Fork 107
/
grouped_list.dart
290 lines (255 loc) · 9.05 KB
/
grouped_list.dart
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
library grouped_list;
import 'dart:collection';
import 'package:flutter/widgets.dart';
/// A groupable list of widgets similar to [ListView], execpt that the
/// items can be sectioned into groups.
///
/// See [ListView.builder]
class GroupedListView<T, E> extends StatefulWidget {
final Key key;
/// Items of which [itemBuilder] or [indexedItemBuilder] produce the list.
final List<T> elements;
/// Defines which elements are grouped together.
///
/// Function is called for each element, when equal for two elements, those two belong the same group.
final E Function(T element) groupBy;
/// Called to build group separators for each group.
/// value is always the groupBy result from the first element of the group.
final Widget Function(E value) groupSeparatorBuilder;
/// Called to build children for the list with
/// 0 <= element < elements.length.
final Widget Function(BuildContext context, T element) itemBuilder;
/// Called to build children for the list with
/// 0 <= element, index < elements.length
final Widget Function(BuildContext context, T element, int index)
indexedItemBuilder;
/// Whether the view scrolls in the reading direction.
///
/// Defaults to ASC.
final GroupedListOrder order;
/// Whether the elements will be sorted or not. IF not it must be done manually.
///
/// Defauts to true.
final bool sort;
/// When set to true the group header of the current visible group will stick on top.
final bool useStickyGroupSeparators;
/// Called to build separators for between each item in the list.
final Widget separator;
/// Whether the group headers float over the list or occupy their own space.
final bool floatingHeader;
/// An object that can be used to control the position to which this scroll view is scrolled.
///
/// See [ScrollView.controller]
final ScrollController controller;
/// The axis along which the scroll view scrolls.
///
/// Defaults to [Axis.vertical].
final Axis scrollDirection;
/// Whether this is the primary scroll view associated with the parent
/// [PrimaryScrollController].
///
/// See [ScrollView.primary]
final bool primary;
/// How the scroll view should respond to user input.
///
/// See [ScrollView.physics].
final ScrollPhysics physics;
/// Whether the extent of the scroll view in the [scrollDirection] should be
/// determined by the contents being viewed.
///
/// See [ScrollView.shrinkWrap]
final bool shrinkWrap;
/// The amount of space by which to inset the children.
final EdgeInsetsGeometry padding;
/// Whether to wrap each child in an [AutomaticKeepAlive].
///
/// See [SliverChildBuilderDelegate.addAutomaticKeepAlives].
final bool addAutomaticKeepAlives;
/// Whether to wrap each child in a [RepaintBoundary].
///
/// See [SliverChildBuilderDelegate.addRepaintBoundaries].
final bool addRepaintBoundaries;
/// Whether to wrap each child in an [IndexedSemantics].
///
/// See [SliverChildBuilderDelegate.addSemanticIndexes].
final bool addSemanticIndexes;
/// Creates a scrollable, linear array of widgets that are created on demand.
///
/// See [ScrollView.cacheExtent]
final double cacheExtent;
/// Creates a [GroupedListView]
GroupedListView({
@required this.elements,
@required this.groupBy,
@required this.groupSeparatorBuilder,
this.itemBuilder,
this.indexedItemBuilder,
this.order = GroupedListOrder.ASC,
this.sort = true,
this.useStickyGroupSeparators = false,
this.separator = const SizedBox.shrink(),
this.floatingHeader = false,
this.key,
this.scrollDirection = Axis.vertical,
this.controller,
this.primary,
this.physics,
this.shrinkWrap = false,
this.padding,
this.addAutomaticKeepAlives = true,
this.addRepaintBoundaries = true,
this.addSemanticIndexes = true,
this.cacheExtent,
}) : super(key: key);
@override
State<StatefulWidget> createState() => _GroupedListViewState<T, E>();
}
class _GroupedListViewState<T, E> extends State<GroupedListView<T, E>> {
ScrollController _controller;
Map<String, GlobalKey> _keys = LinkedHashMap<String, GlobalKey>();
GlobalKey _groupHeaderKey;
List<T> _sortedElements = [];
GlobalKey _key = GlobalKey();
E _topElementIndex;
RenderBox headerBox;
RenderBox listBox;
@override
void dispose() {
_controller.removeListener(_scrollListener);
if (widget.controller == null) {
_controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
this._sortedElements = _sortElements();
return Stack(
key: _key,
alignment: Alignment.topCenter,
children: <Widget>[
ListView.builder(
key: widget.key,
scrollDirection: widget.scrollDirection,
controller: _getController(),
primary: widget.primary,
physics: widget.physics,
shrinkWrap: widget.shrinkWrap,
padding: widget.padding,
itemCount: _sortedElements.length * 2,
addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
addRepaintBoundaries: widget.addRepaintBoundaries,
addSemanticIndexes: widget.addSemanticIndexes,
cacheExtent: widget.cacheExtent,
itemBuilder: (context, index) {
int actualIndex = index ~/ 2;
if (index == 0) {
return Opacity(
opacity: widget.useStickyGroupSeparators ? 0 : 1,
child: widget.groupSeparatorBuilder(
widget.groupBy(_sortedElements[actualIndex])),
);
}
if (index.isEven) {
E curr = widget.groupBy(_sortedElements[actualIndex]);
E prev = widget.groupBy(_sortedElements[actualIndex - 1]);
if (prev != curr) {
return widget.groupSeparatorBuilder(
widget.groupBy(_sortedElements[actualIndex]));
}
return widget.separator;
}
return _buildItem(context, actualIndex);
},
),
_showFixedGroupHeader(),
],
);
}
Container _buildItem(context, int actualIndex) {
GlobalKey key = GlobalKey();
_keys['$actualIndex'] = key;
return Container(
key: key,
child: widget.indexedItemBuilder == null
? widget.itemBuilder(context, _sortedElements[actualIndex])
: widget.indexedItemBuilder(
context, _sortedElements[actualIndex], actualIndex));
}
ScrollController _getController() {
_controller =
widget.controller == null ? ScrollController() : widget.controller;
if (widget.useStickyGroupSeparators) {
_controller.addListener(_scrollListener);
}
return _controller;
}
_scrollListener() {
listBox ??= _key?.currentContext?.findRenderObject();
double listPos = listBox?.localToGlobal(Offset.zero)?.dy ?? 0;
headerBox ??= _groupHeaderKey?.currentContext?.findRenderObject();
double headerHeight = headerBox?.size?.height ?? 0;
double max = double.negativeInfinity;
String topItemKey = '0';
for (var entry in _keys.entries) {
var key = entry.value;
if (_isListItemRendered(key)) {
RenderBox itemBox = key.currentContext.findRenderObject();
double y =
itemBox.localToGlobal(Offset(0, -listPos - 2 * headerHeight)).dy;
if (y <= 0 && y > max) {
topItemKey = entry.key;
max = y;
}
}
}
var index = int.parse(topItemKey);
if (index != _topElementIndex) {
E curr = widget.groupBy(_sortedElements[index]);
if (_topElementIndex != curr) {
setState(() {
_topElementIndex = curr;
});
}
}
}
List<T> _sortElements() {
List<T> elements = widget.elements;
if (widget.sort && elements.isNotEmpty) {
elements.sort((e1, e2) {
var compareResult;
if (widget.groupBy(e1) is Comparable) {
compareResult = (widget.groupBy(e1) as Comparable)
.compareTo(widget.groupBy(e2) as Comparable);
}
if ((compareResult == null || compareResult == 0) && e1 is Comparable) {
compareResult = (e1).compareTo(e2);
}
return compareResult;
});
if (widget.order == GroupedListOrder.DESC) {
elements = elements.reversed.toList();
}
}
return elements;
}
Widget _showFixedGroupHeader() {
_groupHeaderKey = GlobalKey();
if (widget.useStickyGroupSeparators && widget.elements.length > 0) {
_topElementIndex ??= widget.groupBy(_sortedElements[0]);
return Container(
key: _groupHeaderKey,
color: widget.floatingHeader ? null : Color(0xffF7F7F7),
width: widget.floatingHeader ? null : MediaQuery.of(context).size.width,
child: widget.groupSeparatorBuilder(_topElementIndex),
);
}
return Container();
}
bool _isListItemRendered(GlobalKey<State<StatefulWidget>> key) {
return key.currentContext != null &&
key.currentContext.findRenderObject() != null;
}
}
/// Used to define the order of a [GroupedListView].
enum GroupedListOrder { ASC, DESC }