-
-
Notifications
You must be signed in to change notification settings - Fork 313
/
selectDialog.dart
368 lines (330 loc) · 10.8 KB
/
selectDialog.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import 'dart:async';
import 'package:flutter/material.dart';
import '../dropdown_search.dart';
class SelectDialog<T> extends StatefulWidget {
final T selectedValue;
final List<T> items;
final bool showSearchBox;
final bool isFilteredOnline;
final ValueChanged<T> onChanged;
final DropdownSearchOnFind<T> onFind;
final DropdownSearchPopupItemBuilder<T> itemBuilder;
final InputDecoration searchBoxDecoration;
final DropdownSearchItemAsString<T> itemAsString;
final DropdownSearchFilterFn<T> filterFn;
final String hintText;
final double maxHeight;
final double dialogMaxWidth;
final Widget popupTitle;
final bool showSelectedItem;
final DropdownSearchCompareFn<T> compareFn;
final DropdownSearchPopupItemEnabled<T> itemDisabled;
///custom layout for empty results
final EmptyBuilder emptyBuilder;
///custom layout for loading items
final LoadingBuilder loadingBuilder;
///custom layout for error
final ErrorBuilder errorBuilder;
///the search box will be focused if true
final bool autoFocusSearchBox;
///text controller to set default search word for example
final TextEditingController searchBoxController;
///delay before searching
final Duration searchDelay;
const SelectDialog({
Key key,
this.popupTitle,
this.items,
this.maxHeight,
this.showSearchBox = false,
this.isFilteredOnline = false,
this.onChanged,
this.selectedValue,
this.onFind,
this.itemBuilder,
this.searchBoxDecoration,
this.hintText,
this.itemAsString,
this.filterFn,
this.showSelectedItem = false,
this.compareFn,
this.emptyBuilder,
this.loadingBuilder,
this.errorBuilder,
this.autoFocusSearchBox = false,
this.dialogMaxWidth,
this.itemDisabled,
this.searchBoxController,
this.searchDelay,
}) : super(key: key);
@override
_SelectDialogState<T> createState() => _SelectDialogState<T>();
}
class _SelectDialogState<T> extends State<SelectDialog<T>> {
final FocusNode focusNode = new FocusNode();
final StreamController<List<T>> _itemsStream = StreamController();
final ValueNotifier<bool> _loadingNotifier = ValueNotifier(false);
final List<T> _items = List<T>();
Debouncer _debouncer;
@override
void initState() {
super.initState();
_debouncer = Debouncer(delay: widget.searchDelay);
Future.delayed(
Duration.zero,
() => manageItemsByFilter(widget.searchBoxController?.text ?? '',
isFistLoad: true),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (widget.autoFocusSearchBox)
FocusScope.of(context).requestFocus(focusNode);
}
@override
void dispose() {
_itemsStream.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
Size deviceSize = MediaQuery.of(context).size;
bool isTablet = deviceSize.width > deviceSize.height;
double maxHeight = deviceSize.height * (isTablet ? .8 : .6);
double maxWidth = deviceSize.width * (isTablet ? .7 : .9);
return Container(
width: widget.dialogMaxWidth ?? maxWidth,
constraints: BoxConstraints(maxHeight: widget.maxHeight ?? maxHeight),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_searchField(),
Expanded(
child: Stack(
children: <Widget>[
StreamBuilder<List<T>>(
stream: _itemsStream.stream,
builder: (context, snapshot) {
if (snapshot.hasError) {
return _errorWidget(snapshot?.error);
} else if (!snapshot.hasData) {
return _loadingWidget();
} else if (snapshot.data.isEmpty) {
if (widget.emptyBuilder != null)
return widget.emptyBuilder(
context, widget.searchBoxController?.text);
else
return const Center(
child: const Text("No data found"),
);
}
return ListView.builder(
shrinkWrap: true,
padding: EdgeInsets.symmetric(vertical: 0),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var item = snapshot.data[index];
return _itemWidget(item);
},
);
},
),
_loadingWidget()
],
),
),
],
),
);
}
void _showErrorDialog(dynamic error) {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error while getting online items"),
content: _errorWidget(error),
actions: <Widget>[
FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop(false);
},
)
],
);
},
);
}
Widget _errorWidget(dynamic error) {
if (widget.errorBuilder != null)
return widget.errorBuilder(
context, widget.searchBoxController?.text, error);
else
return Padding(
padding: EdgeInsets.all(8),
child: Text(
error?.toString() ?? 'Error',
),
);
}
Widget _loadingWidget() {
return ValueListenableBuilder(
valueListenable: _loadingNotifier,
builder: (context, bool isLoading, wid) {
if (isLoading) {
if (widget.loadingBuilder != null)
return widget.loadingBuilder(
context, widget.searchBoxController?.text);
else
return Padding(
padding: const EdgeInsets.all(24.0),
child: const Center(
child: const CircularProgressIndicator(),
),
);
}
return Container();
});
}
void _onTextChanged(String filter) async {
manageItemsByFilter(filter);
}
///Function that filter item (online and offline) base on user filter
///[filter] is the filter keyword
///[isFirstLoad] true if it's the first time we load data from online, false other wises
void manageItemsByFilter(String filter, {bool isFistLoad = false}) async {
_loadingNotifier.value = true;
List<T> applyFilter(String filter) {
return _items.where((i) {
if (widget.filterFn != null)
return (widget.filterFn(i, filter));
else if (i.toString().toLowerCase().contains(filter.toLowerCase()))
return true;
else if (widget.itemAsString != null) {
return (widget.itemAsString(i))
?.toLowerCase()
?.contains(filter.toLowerCase()) ??
false;
}
return false;
}).toList();
}
//load offline data for the first time
if (isFistLoad && widget.items != null) _items.addAll(widget.items);
//manage offline items
if (widget.onFind != null && (widget.isFilteredOnline || isFistLoad)) {
try {
final List<T> onlineItems = List();
onlineItems.addAll(await widget.onFind(filter) ?? List());
//Remove all old data
_items.clear();
//add offline items
if (widget.items != null) _items.addAll(widget.items);
//add new online items to list
_items.addAll(onlineItems);
_addDataToStream(applyFilter(filter));
} catch (e) {
_addErrorToStream(e);
//if offline items count > 0 , the error will be not visible for the user
//As solution we show it in dialog
if (widget.items != null && widget.items.isNotEmpty) {
_showErrorDialog(e);
_addDataToStream(applyFilter(filter));
}
}
} else {
_addDataToStream(applyFilter(filter));
}
_loadingNotifier.value = false;
}
void _addDataToStream(List<T> data) {
if (_itemsStream.isClosed) return;
_itemsStream.add(data);
}
void _addErrorToStream(Object error, [StackTrace stackTrace]) {
if (_itemsStream.isClosed) return;
_itemsStream.addError(error, stackTrace);
}
Widget _itemWidget(T item) {
if (widget.itemBuilder != null)
return InkWell(
child: widget.itemBuilder(
context,
item,
_manageSelectedItemVisibility(item),
),
onTap: widget.itemDisabled != null &&
(widget.itemDisabled(item) ?? false) == true
? null
: () {
Navigator.pop(context, item);
if (widget.onChanged != null) widget.onChanged(item);
},
);
else
return ListTile(
title: Text(
widget.itemAsString != null
? (widget.itemAsString(item) ?? "")
: item.toString(),
),
selected: _manageSelectedItemVisibility(item),
onTap: widget.itemDisabled != null &&
(widget.itemDisabled(item) ?? false) == true
? null
: () {
Navigator.pop(context, item);
if (widget.onChanged != null) widget.onChanged(item);
},
);
}
/// selected item will be highlighted only when [widget.showSelectedItem] is true,
/// if our object is String [widget.compareFn] is not required , other wises it's required
bool _manageSelectedItemVisibility(T item) {
if (!widget.showSelectedItem) return false;
if (T == String) {
return item == widget.selectedValue;
} else {
return widget.compareFn(item, widget.selectedValue);
}
}
Widget _searchField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
widget.popupTitle ?? const SizedBox.shrink(),
if (widget.showSearchBox)
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: widget.searchBoxController,
focusNode: focusNode,
onChanged: (f) => _debouncer(() {
_onTextChanged(f);
}),
decoration: widget.searchBoxDecoration ??
InputDecoration(
hintText: widget.hintText,
border: const OutlineInputBorder(),
contentPadding:
const EdgeInsets.symmetric(horizontal: 16),
),
),
)
]);
}
}
class Debouncer {
final Duration delay;
Timer _timer;
Debouncer({this.delay});
call(Function action) {
_timer?.cancel();
_timer = Timer(delay ?? const Duration(milliseconds: 500), action);
}
}